Giter Club home page Giter Club logo

react-map-gl-geocoder's Introduction

react-map-gl-geocoder

React wrapper for mapbox-gl-geocoder for use with react-map-gl.

NPM react-map-gl-geocoder

Demos

Installation

npm

$ npm install react-map-gl-geocoder

or

Yarn

$ yarn add react-map-gl-geocoder

Styling

Import:

import 'react-map-gl-geocoder/dist/mapbox-gl-geocoder.css'

or

Link tag in header:

<link href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.2.0/mapbox-gl-geocoder.css' rel='stylesheet' />

Props

Only mapRef and mapboxApiAccessToken are required.

All non-primitive prop values besides mapRef and containerRef should be memoized.

Name Type Default Description
mapRef Object Ref for react-map-gl map component.
containerRef Object This can be used to place the geocoder outside of the map. The position prop is ignored if this is passed in. Example: https://codesandbox.io/s/v0m14q5rly
onViewportChange Function () => {} Is passed updated viewport values after executing a query.
mapboxApiAccessToken String https://www.mapbox.com/
inputValue String Sets the search input value
origin String "https://api.mapbox.com" Use to set a custom API origin.
zoom Number 16 On geocoded result what zoom level should the map animate to when a bbox isn't found in the response. If a bbox is found the map will fit to the bbox.
placeholder String "Search" Override the default placeholder attribute value.
proximity Object A proximity argument: this is a geographical point given as an object with latitude and longitude properties. Search results closer to this point will be given higher priority.
trackProximity Boolean false If true, the geocoder proximity will automatically update based on the map view.
collapsed Boolean false If true, the geocoder control will collapse until hovered or in focus.
clearAndBlurOnEsc Boolean false If true, the geocoder control will clear it's contents and blur when user presses the escape key.
clearOnBlur Boolean false If true, the geocoder control will clear its value when the input blurs.
bbox Array A bounding box argument: this is a bounding box given as an array in the format [minX, minY, maxX, maxY]. Search results will be limited to the bounding box.
types String A comma seperated list of types that filter results to match those specified. See https://www.mapbox.com/developers/api/geocoding/#filter-type for available types.
countries String A comma separated list of country codes to limit results to specified country or countries.
minLength Number 2 Minimum number of characters to enter before results are shown.
limit Number 5 Maximum number of results to show.
language String Specify the language to use for response text and query result weighting. Options are IETF language tags comprised of a mandatory ISO 639-1 language code and optionally one or more IETF subtags for country or script. More than one value can also be specified, separated by commas.
filter Function A function which accepts a Feature in the Carmen GeoJSON format to filter out results from the Geocoding API response before they are included in the suggestions list. Return true to keep the item, false otherwise.
localGeocoder Function A function accepting the query string which performs local geocoding to supplement results from the Mapbox Geocoding API. Expected to return an Array of GeoJSON Features in the Carmen GeoJSON format.
localGeocoderOnly Boolean false If true, indicates that the localGeocoder results should be the only ones returned to the user. If false, indicates that the localGeocoder results should be combined with those from the Mapbox API with the localGeocoder results ranked higher.
reverseGeocode Boolean false Enable reverse geocoding. Defaults to false. Expects coordinates to be lat, lon.
enableEventLogging Boolean true Allow Mapbox to collect anonymous usage statistics from the plugin.
marker Boolean or Object true If true, a Marker will be added to the map at the location of the user-selected result using a default set of Marker options. If the value is an object, the marker will be constructed using these options. If false, no marker will be added to the map.
render Function A function that specifies how the results should be rendered in the dropdown menu. Accepts a single Carmen GeoJSON object as input and return a string. Any html in the returned string will be rendered. Uses mapbox-gl-geocoder's default rendering if no function provided.
position String "top-right" Position on the map to which the geocoder control will be added. Valid values are "top-left", "top-right", "bottom-left", and "bottom-right".
onInit Function () => {} Is passed Mapbox geocoder instance as param and is executed after Mapbox geocoder is initialized.
onClear Function () => {} Executed when the input is cleared.
onLoading Function () => {} Is passed { query } as a param and is executed when the geocoder is looking up a query.
onResults Function () => {} Is passed { results } as a param and is executed when the geocoder returns a response.
onResult Function () => {} Is passed { result } as a param and is executed when the geocoder input is set.
onError Function () => {} Is passed { error } as a param and is executed when an error occurs with the geocoder.

Examples

Simple Example

import 'mapbox-gl/dist/mapbox-gl.css'
import 'react-map-gl-geocoder/dist/mapbox-gl-geocoder.css'
import React, { useState, useRef, useCallback } from 'react'
import MapGL from 'react-map-gl'
import Geocoder from 'react-map-gl-geocoder'

// Ways to set Mapbox token: https://uber.github.io/react-map-gl/#/Documentation/getting-started/about-mapbox-tokens
const MAPBOX_TOKEN = 'REPLACE_WITH_YOUR_MAPBOX_TOKEN'

const Example = () => {
  const [viewport, setViewport] = useState({
    latitude: 37.7577,
    longitude: -122.4376,
    zoom: 8
  });
  const mapRef = useRef();
  const handleViewportChange = useCallback(
    (newViewport) => setViewport(newViewport),
    []
  );

  // if you are happy with Geocoder default settings, you can just use handleViewportChange directly
  const handleGeocoderViewportChange = useCallback(
    (newViewport) => {
      const geocoderDefaultOverrides = { transitionDuration: 1000 };

      return handleViewportChange({
        ...newViewport,
        ...geocoderDefaultOverrides
      });
    },
    []
  );

  return (
    <div style={{ height: "100vh" }}>
      <MapGL
        ref={mapRef}
        {...viewport}
        width="100%"
        height="100%"
        onViewportChange={handleViewportChange}
        mapboxApiAccessToken={MAPBOX_TOKEN}
      >
        <Geocoder
          mapRef={mapRef}
          onViewportChange={handleGeocoderViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          position="top-left"
        />
      </MapGL>
    </div>
  );
};

export default Example

Ignore Map Events Example

You can use the containerRef prop to place the Geocoder component outside of the MapGL component to avoid propagating the mouse events to the MapGL component. You can use CSS to position it over the map as shown in this example.

import 'mapbox-gl/dist/mapbox-gl.css'
import 'react-map-gl-geocoder/dist/mapbox-gl-geocoder.css'
import React, { useState, useRef, useCallback } from 'react'
import MapGL from 'react-map-gl'
import Geocoder from 'react-map-gl-geocoder'

// Ways to set Mapbox token: https://uber.github.io/react-map-gl/#/Documentation/getting-started/about-mapbox-tokens
const MAPBOX_TOKEN = 'REPLACE_WITH_YOUR_MAPBOX_TOKEN'

const Example = () => {
  const [viewport, setViewport] = useState({
    latitude: 37.7577,
    longitude: -122.4376,
    zoom: 8,
  });
  const geocoderContainerRef = useRef();
  const mapRef = useRef();
  const handleViewportChange = useCallback(
    (newViewport) => setViewport(newViewport),
    []
  );

  return (
    <div style={{ height: "100vh" }}>
      <div
        ref={geocoderContainerRef}
        style={{ position: "absolute", top: 20, left: 20, zIndex: 1 }}
      />
      <MapGL
        ref={mapRef}
        {...viewport}
        width="100%"
        height="100%"
        onViewportChange={handleViewportChange}
        mapboxApiAccessToken={MAPBOX_TOKEN}
      >
        <Geocoder
          mapRef={mapRef}
          containerRef={geocoderContainerRef}
          onViewportChange={handleViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          position="top-left"
        />
      </MapGL>
    </div>
  );
};

Sample Screenshot

react-map-gl-geocoder example screenshot

react-map-gl-geocoder's People

Contributors

dependabot[bot] avatar jaronheard avatar petispaespea avatar samsamskies avatar wfendler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-map-gl-geocoder's Issues

reverseGeocode not working

I'm trying to display the address of the location on click but it's not showing in the geocoder.

 <MapGl
      {...viewport}
      ref={mapRef}
      mapboxApiAccessToken={token}
      onViewportChange={viewState => setViewport(viewState)}
      transitionInterpolator={new FlyToInterpolator()}
      onClick={e => {
         handleGeocoderViewportChange({ latitude: e.lngLat[1], longitude: e.lngLat[0] });
    >
      <Geocoder
        mapRef={mapRef}
        mapboxApiAccessToken={token}
        onViewportChange={handleGeocoderViewportChange}
        proximity={{ ...viewport }}
        trackProximity
        reverseGeocode
      />
  </MapGl>

Pixel project matrix not invertible error

When I am trying to search some places(like country names), viewport does not update and I receive next error:
Uncaught Error: Pixel project matrix not invertible
at WebMercatorViewport.Viewport (viewport.js:38)
at new WebMercatorViewport (web-mercator-viewport.js:61)
at fitBounds (index.js:42)
at EventEmitter.Geocoder._this.handleResult (index.js:201)
at EventEmitter../node_modules/events/events.js.EventEmitter.emit (events.js:81)
at MapboxGeocoder._onChange (index.js:162)
at Suggestions../node_modules/suggestions/src/suggestions.js.Suggestions.value (suggestions.js:174)
at List../node_modules/suggestions/src/list.js.List.handleMouseUp (list.js:77)
at List. (list.js:71)

On the other hand, when I type city name, everything is fine.
What may cause it and how to fix ?
My code is here https://github.com/NetisGod/Viewpoints-app

Set input to show only part of the result

Hi,

First, thank you for all the hard work.

Is there a way I can show only a part of the result in input field? For example, after selecting a value from the dropdown Orlando International Airport, Orlando, Florida 32827, United States, the input field shows only Orlando International Airport.

I tried to set it manually in onResult , but the input is back to the original value after the component reloads.

Thank you.

MapGL viewport does not update when location changed with geocoder

In your example code, the MapGL viewport state does not update when a location is changed in the geocoder, and I don't think there is an easy way to do it with your module as structured.

When the location is updated from the geocoder, the state of the MapGL component will not be up to date with the map, and if you're doing anything else that relies on the viewport (e.g. Deck.GL layers), you'll have issues.

NavigationControl in react-map-gl implements an onViewportChange prop, which I think is a pattern that could be implemented here.
https://github.com/uber/react-map-gl/blob/master/src/components/navigation-control.js

This forked sandbox logs viewport adds NavigationControl showing use of the onViewportChange prop and logs viewport to the console.
https://codesandbox.io/s/1zk0wz3n87

I could work up a PR if you'd prefer.

CSS Error in mapbox-gl-geocoder

After incorporating this library, I keep getting the following error:

./node_modules/react-map-gl-geocoder/node_modules/@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css 2:0
Module parse failed: Unexpected token (2:0)
You may need an appropriate loader to handle this file type.
| /* Basics */
> .mapboxgl-ctrl-geocoder,
| .mapboxgl-ctrl-geocoder *,
| .mapboxgl-ctrl-geocoder *:after,

The React app uses the NextJS framework (v8.0.4) and react-map-gl-geocoder version 1.8.0.

I'm guessing this could be a webpack config related problem since NextJS manages webpack for you. I will see if I can come up with anything there and report back.

viewport-mercator-project: assertion failed.

After click on a result from the geocoder, I'm getting this error:

assert.js:3 Uncaught Error: viewport-mercator-project: assertion failed.
    at assert (assert.js:3)
    at pixelsToWorld (web-mercator-utils.js:194)
    at WebMercatorViewport.unproject (viewport.js:102)
    at InteractiveMap._onMouseClick (interactive-map.js:265)
    at Array.<anonymous> (event-manager.js:360)
    at Manager.emit (hammer.js:2525)
    at TapRecognizer.emit (hammer.js:2130)
    at TapRecognizer.tryEmit (hammer.js:1572)
    at TapRecognizer.<anonymous> (hammer.js:2109)
    at boundFn (hammer.js:197)

And the whole screen is turning white.

On result handler

Hello,

Separate question from my other one (#8), how do I add a onResults or onResult handler to the component?

queryParams prop seems ignored

Hello and thanks for this nice library!
I'm passing a queryParams prop to geocoder but it doesn't change the request. Am I doing it wrong?

const bbox = {
  ne: { lng: -34.31067179238596, lat: 46.03500843336249 },
  sw: { lng: -113.41223429238529, lat: -9.32997469975038 },
};

const center = {
  latitude: 20.827873989993776,
  longitude: -73.86145304236818,
};

const queryParams = {
  bbox: [bbox.sw.lng, bbox.sw.lat, bbox.ne.lng, bbox.sw.lng],
  proximity: [center.longitude, center.latitude],
};
<Geocoder
  mapboxApiAccessToken={mapboxApiAccessToken}
  mapRef={this.mapRef}
  containerRef={this.geocoderContainerRef}
  queryParams={queryParams}
  clearAndBlurOnEsc
  onViewportChange={this.onViewportChange}
/>

Result in network console stays the same and does not include my params:

https://api.mapbox.com/geocoding/v5/mapbox.places/me.json?limit=5&language=fr-FR&access_token=[secret]

Adding Geocode component generates bunch of errors

The errors occur only when adding the Geocoder component.

import React from "react"

import "react-map-gl-geocoder/dist/mapbox-gl-geocoder.css"
import "mapbox-gl/dist/mapbox-gl.css"

import ReactMapGL from "react-map-gl"
import Geocoder from "react-map-gl-geocoder"


export default function StationMap() {
  const settings = {
    dragPan: true,
    dragRotate: true,
    scrollZoom: false,
    touchZoom: true,
    touchRotate: true,
    keyboard: true,
    doubleClickZoom: true,
    minZoom: 0,
    maxZoom: 20,
    minPitch: 0,
    maxPitch: 85,
  }

  const [viewport, setViewport] = React.useState({
    latitude: 42.444,
    longitude: -76.5019,
    zoom: 8,
    width: "100%",
    height: "100%",
  })


  const myMap = React.createRef()

  return (
   <ReactMapGL
     ref={myMap}
     {...viewport}
     {...settings}
     mapboxApiAccessToken={process.env.GATSBY_MAPBOX_TOKEN}
     mapStyle="mapbox://styles/mapbox/streets-v11"
     onViewportChange={viewport => setViewport(viewport)}
   >
     <Geocoder
       mapRef={myMap}
       mapboxApiAccessToken={process.env.GATSBY_MAPBOX_TOKEN}
     >
     </Geocoder>
</ReactMapGL>
  )
}

The log with the errors:

index.m.js:1 Uncaught TypeError: Cannot read property 'addControl' of null
    at i.e.initializeGeocoder (index.m.js:1)
    at i.o.componentDidMount (index.m.js:1)
    at i.<anonymous> (react-hot-loader.development.js:704)
    at commitLifeCycles (react-dom.development.js:21963)
    at commitLayoutEffects (react-dom.development.js:25287)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at commitRootImpl (react-dom.development.js:25023)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at commitRoot (react-dom.development.js:24864)
    at finishSyncRender (react-dom.development.js:24250)
    at performSyncWorkOnRoot (react-dom.development.js:24222)
    at react-dom.development.js:12239
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12234)
    at flushSyncCallbackQueue (react-dom.development.js:12222)
    at flushPassiveEffectsImpl (react-dom.development.js:25367)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushPassiveEffects (react-dom.development.js:25304)
    at react-dom.development.js:25183
    at workLoop (scheduler.development.js:759)
    at flushWork (scheduler.development.js:714)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:219)
e.initializeGeocoder @ index.m.js:1
o.componentDidMount @ index.m.js:1
componentDidMount @ react-hot-loader.development.js:704
commitLifeCycles @ react-dom.development.js:21963
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
index.m.js:1 Uncaught TypeError: Cannot read property 'remove' of undefined
    at Gt.off (index.m.js:1)
    at i.e.unsubscribeEvents (index.m.js:1)
    at i.e.removeGeocoder (index.m.js:1)
    at i.o.componentWillUnmount (index.m.js:1)
    at i.<anonymous> (react-hot-loader.development.js:704)
    at callComponentWillUnmountWithTimer (react-dom.development.js:21756)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at safelyCallComponentWillUnmount (react-dom.development.js:21763)
    at commitUnmount (react-dom.development.js:22256)
    at commitNestedUnmounts (react-dom.development.js:22350)
    at unmountHostComponents (react-dom.development.js:22682)
    at commitDeletion (react-dom.development.js:22768)
    at commitMutationEffects (react-dom.development.js:25266)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at commitRootImpl (react-dom.development.js:24989)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at commitRoot (react-dom.development.js:24864)
    at finishSyncRender (react-dom.development.js:24250)
    at performSyncWorkOnRoot (react-dom.development.js:24222)
    at react-dom.development.js:12239
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12234)
    at flushSyncCallbackQueue (react-dom.development.js:12222)
    at flushPassiveEffectsImpl (react-dom.development.js:25367)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushPassiveEffects (react-dom.development.js:25304)
    at react-dom.development.js:25183
    at workLoop (scheduler.development.js:759)
    at flushWork (scheduler.development.js:714)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:219)
off @ index.m.js:1
e.unsubscribeEvents @ index.m.js:1
e.removeGeocoder @ index.m.js:1
o.componentWillUnmount @ index.m.js:1
componentDidMount @ react-hot-loader.development.js:704
callComponentWillUnmountWithTimer @ react-dom.development.js:21756
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
safelyCallComponentWillUnmount @ react-dom.development.js:21763
commitUnmount @ react-dom.development.js:22256
commitNestedUnmounts @ react-dom.development.js:22350
unmountHostComponents @ react-dom.development.js:22682
commitDeletion @ react-dom.development.js:22768
commitMutationEffects @ react-dom.development.js:25266
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:24989
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
Show 7 more frames
index.js:2177 The above error occurred in the <i> component:
    in i (at stationsMap.js:68)
    in div (created by Context.Consumer)
    in div (created by AutoSizer)
    in AutoSizer (created by StaticMap)
    in div (created by StaticMap)
    in StaticMap (created by InteractiveMap)
    in div (created by InteractiveMap)
    in InteractiveMap (at stationsMap.js:59)
    in div (at stationsMap.js:47)
    in div (at stationsMap.js:37)
    in StationMap (at pages/index.js:63)
    in div (at pages/index.js:62)
    in div (at pages/index.js:60)
    in section (at pages/index.js:59)
    in main (at layout.js:24)
    in Layout (at pages/index.js:15)
    in IndexPage (created by HotExportedIndexPage)
    in AppContainer (created by HotExportedIndexPage)
    in HotExportedIndexPage (created by PageRenderer)
    in PageRenderer (at json-store.js:93)
    in JSONStore (at root.js:51)
    in RouteHandler (at root.js:73)
    in div (created by FocusHandlerImpl)
    in FocusHandlerImpl (created by Context.Consumer)
    in FocusHandler (created by RouterImpl)
    in RouterImpl (created by Context.Consumer)
    in Location (created by Context.Consumer)
    in Router (created by EnsureResources)
    in ScrollContext (at root.js:64)
    in RouteUpdates (at root.js:63)
    in EnsureResources (at root.js:61)
    in LocationHandler (at root.js:119)
    in LocationProvider (created by Context.Consumer)
    in Location (at root.js:118)
    in Root (at root.js:126)
    in SessionCheck (at gatsby-browser.js:75)
    in _default (at app.js:67)

React will try to recreate this component tree from scratch using the error boundary you provided, AppContainer.
__stack_frame_overlay_proxy_console__ @ index.js:2177
r @ backend.js:6
logCapturedError @ react-dom.development.js:21703
logError @ react-dom.development.js:21740
callback @ react-dom.development.js:23144
callCallback @ react-dom.development.js:13863
commitUpdateEffects @ react-dom.development.js:13901
commitUpdateQueue @ react-dom.development.js:13889
commitLifeCycles @ react-dom.development.js:21997
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
Show 2 more frames
index.js:2177 TypeError: Cannot read property 'addControl' of null
    at i.e.initializeGeocoder (index.m.js:1)
    at i.o.componentDidMount (index.m.js:1)
    at i.<anonymous> (react-hot-loader.development.js:704)
    at commitLifeCycles (react-dom.development.js:21963)
    at commitLayoutEffects (react-dom.development.js:25287)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at commitRootImpl (react-dom.development.js:25023)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at commitRoot (react-dom.development.js:24864)
    at finishSyncRender (react-dom.development.js:24250)
    at performSyncWorkOnRoot (react-dom.development.js:24222)
    at react-dom.development.js:12239
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12234)
    at flushSyncCallbackQueue (react-dom.development.js:12222)
    at flushPassiveEffectsImpl (react-dom.development.js:25367)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushPassiveEffects (react-dom.development.js:25304)
    at react-dom.development.js:25183
    at workLoop (scheduler.development.js:759)
    at flushWork (scheduler.development.js:714)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:219) "
    in AppContainer (created by HotExportedIndexPage)
    in HotExportedIndexPage (created by PageRenderer)
    in PageRenderer (at json-store.js:93)
    in JSONStore (at root.js:51)
    in RouteHandler (at root.js:73)
    in EnsureResources (at root.js:61)
    in LocationHandler (at root.js:119)
    in LocationProvider (created by Context.Consumer)
    in Context.Consumer (created by Location)
    in Location (at root.js:118)
    in Root (at root.js:126)"
__stack_frame_overlay_proxy_console__ @ index.js:2177
r @ backend.js:6
error @ react-hot-loader.development.js:294
componentDidCatch @ react-hot-loader.development.js:2401
callback @ react-dom.development.js:23149
callCallback @ react-dom.development.js:13863
commitUpdateEffects @ react-dom.development.js:13901
commitUpdateQueue @ react-dom.development.js:13889
commitLifeCycles @ react-dom.development.js:21997
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
Show 2 more frames
index.m.js:1 Uncaught TypeError: Cannot read property 'addControl' of null
    at i.e.initializeGeocoder (index.m.js:1)
    at i.o.componentDidMount (index.m.js:1)
    at i.<anonymous> (react-hot-loader.development.js:704)
    at commitLifeCycles (react-dom.development.js:21963)
    at commitLayoutEffects (react-dom.development.js:25287)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at commitRootImpl (react-dom.development.js:25023)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at commitRoot (react-dom.development.js:24864)
    at finishSyncRender (react-dom.development.js:24250)
    at performSyncWorkOnRoot (react-dom.development.js:24222)
    at react-dom.development.js:12239
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12234)
    at flushSyncCallbackQueue (react-dom.development.js:12222)
    at flushPassiveEffectsImpl (react-dom.development.js:25367)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushPassiveEffects (react-dom.development.js:25304)
    at react-dom.development.js:25183
    at workLoop (scheduler.development.js:759)
    at flushWork (scheduler.development.js:714)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:219)
e.initializeGeocoder @ index.m.js:1
o.componentDidMount @ index.m.js:1
componentDidMount @ react-hot-loader.development.js:704
commitLifeCycles @ react-dom.development.js:21963
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
index.js:2177 The above error occurred in the <AppContainer> component:
    in AppContainer (created by HotExportedIndexPage)
    in HotExportedIndexPage (created by PageRenderer)
    in PageRenderer (at json-store.js:93)
    in JSONStore (at root.js:51)
    in RouteHandler (at root.js:73)
    in div (created by FocusHandlerImpl)
    in FocusHandlerImpl (created by Context.Consumer)
    in FocusHandler (created by RouterImpl)
    in RouterImpl (created by Context.Consumer)
    in Location (created by Context.Consumer)
    in Router (created by EnsureResources)
    in ScrollContext (at root.js:64)
    in RouteUpdates (at root.js:63)
    in EnsureResources (at root.js:61)
    in LocationHandler (at root.js:119)
    in LocationProvider (created by Context.Consumer)
    in Location (at root.js:118)
    in Root (at root.js:126)
    in SessionCheck (at gatsby-browser.js:75)
    in _default (at app.js:67)

React will try to recreate this component tree from scratch using the error boundary you provided, LocationProvider.
__stack_frame_overlay_proxy_console__ @ index.js:2177
r @ backend.js:6
logCapturedError @ react-dom.development.js:21703
logError @ react-dom.development.js:21740
callback @ react-dom.development.js:23144
callCallback @ react-dom.development.js:13863
commitUpdateEffects @ react-dom.development.js:13901
commitUpdateQueue @ react-dom.development.js:13889
commitLifeCycles @ react-dom.development.js:21997
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
Show 2 more frames
index.m.js:1 Uncaught TypeError: Cannot read property 'addControl' of null
    at i.e.initializeGeocoder (index.m.js:1)
    at i.o.componentDidMount (index.m.js:1)
    at i.<anonymous> (react-hot-loader.development.js:704)
    at commitLifeCycles (react-dom.development.js:21963)
    at commitLayoutEffects (react-dom.development.js:25287)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at commitRootImpl (react-dom.development.js:25023)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at commitRoot (react-dom.development.js:24864)
    at finishSyncRender (react-dom.development.js:24250)
    at performSyncWorkOnRoot (react-dom.development.js:24222)
    at react-dom.development.js:12239
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12234)
    at flushSyncCallbackQueue (react-dom.development.js:12222)
    at flushPassiveEffectsImpl (react-dom.development.js:25367)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushPassiveEffects (react-dom.development.js:25304)
    at react-dom.development.js:25183
    at workLoop (scheduler.development.js:759)
    at flushWork (scheduler.development.js:714)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:219)
e.initializeGeocoder @ index.m.js:1
o.componentDidMount @ index.m.js:1
componentDidMount @ react-hot-loader.development.js:704
commitLifeCycles @ react-dom.development.js:21963
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
index.js:2177 The above error occurred in the <LocationProvider> component:
    in LocationProvider (created by Context.Consumer)
    in Location (at root.js:118)
    in Root (at root.js:126)
    in SessionCheck (at gatsby-browser.js:75)
    in _default (at app.js:67)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
__stack_frame_overlay_proxy_console__ @ index.js:2177
r @ backend.js:6
logCapturedError @ react-dom.development.js:21703
logError @ react-dom.development.js:21740
update.callback @ react-dom.development.js:23108
callCallback @ react-dom.development.js:13863
commitUpdateEffects @ react-dom.development.js:13901
commitUpdateQueue @ react-dom.development.js:13889
commitLifeCycles @ react-dom.development.js:22022
commitLayoutEffects @ react-dom.development.js:25287
callCallback @ react-dom.development.js:363
invokeGuardedCallbackDev @ react-dom.development.js:412
invokeGuardedCallback @ react-dom.development.js:467
commitRootImpl @ react-dom.development.js:25023
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
commitRoot @ react-dom.development.js:24864
finishSyncRender @ react-dom.development.js:24250
performSyncWorkOnRoot @ react-dom.development.js:24222
(anonymous) @ react-dom.development.js:12239
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushSyncCallbackQueueImpl @ react-dom.development.js:12234
flushSyncCallbackQueue @ react-dom.development.js:12222
flushPassiveEffectsImpl @ react-dom.development.js:25367
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12189
flushPassiveEffects @ react-dom.development.js:25304
(anonymous) @ react-dom.development.js:25183
workLoop @ scheduler.development.js:759
flushWork @ scheduler.development.js:714
performWorkUntilDeadline @ scheduler.development.js:219
Show 2 more frames
index.m.js:1 Uncaught TypeError: Cannot read property 'addControl' of null
    at i.e.initializeGeocoder (index.m.js:1)
    at i.o.componentDidMount (index.m.js:1)
    at i.<anonymous> (react-hot-loader.development.js:704)
    at commitLifeCycles (react-dom.development.js:21963)
    at commitLayoutEffects (react-dom.development.js:25287)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:467)
    at commitRootImpl (react-dom.development.js:25023)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at commitRoot (react-dom.development.js:24864)
    at finishSyncRender (react-dom.development.js:24250)
    at performSyncWorkOnRoot (react-dom.development.js:24222)
    at react-dom.development.js:12239
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12234)
    at flushSyncCallbackQueue (react-dom.development.js:12222)
    at flushPassiveEffectsImpl (react-dom.development.js:25367)
    at unstable_runWithPriority (scheduler.development.js:815)
    at runWithPriority$2 (react-dom.development.js:12189)
    at flushPassiveEffects (react-dom.development.js:25304)
    at react-dom.development.js:25183
    at workLoop (scheduler.development.js:759)
    at flushWork (scheduler.development.js:714)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:219)

Could not find declaration for module

I can't run my app because the import proccess always says
"Could not find a declaration file for module 'react-map-gl-geocoder'. '/..../app-map/node_modules/react-map-gl-geocoder/dist/index.js' implicitly has an 'any' type."

Can you help me how to fix it?

I had install the react-map-gl-geocoder

line_20190909_174732

Uncaught TypeError: EventEmitter is not a constructor

Hi there,

I copied the code from https://codesandbox.io/s/vv29y730q3 to my project and getting this error from the MapboxGeocoder constructor:

Uncaught TypeError: EventEmitter is not a constructor
    at new MapboxGeocoder (index.js?b9d5:43)
    at Geocoder._this.initializeGeocoder (index.js?05ab:98)
    at Geocoder.componentDidMount (index.js?05ab:231)
    at commitLifeCycles (react-dom.development.js?9a03:17128)
    at commitAllLifeCycles (react-dom.development.js?9a03:18530)
    at HTMLUnknownElement.callCallback (react-dom.development.js?9a03:149)

"react": "^16.8.2",
"react-map-gl": "^4.0.13",
"react-map-gl-geocoder": "^1.6.4"

Thank you.

kepler.gl implementation

Do you know how I could implement this into kepler.gl's module?

I tried this.... but no luck

`

import React, {Component} from 'react';
import {connect} from 'react-redux';

import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
import KeplerGl from 'kepler.gl';
const MAPBOX_TOKEN = 'XXXX'; // eslint-disable-line
import Geocoder from 'react-map-gl-geocoder'

class App extends Component {

render() {
return (
<div style={{position: 'absolute', width: '100%', height: '100%', minHeight: '70vh'}}>

{({height, width}) => (

        <KeplerGl
          mapboxApiAccessToken={MAPBOX_TOKEN}
          id="map"
          ref={this.mapRef}
          width={width}
          height={height}
        >
        <Geocoder
          mapRef={this.mapRef}
          onViewportChange={this.handleGeocoderViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          position="top-left"
          
        />
        </KeplerGl>
      )}
    </AutoSizer>
    
  </div>
);

}
}

const mapStateToProps = state => state;
const dispatchToProps = dispatch => ({dispatch});

export default connect(mapStateToProps, dispatchToProps)(App);
`

Using componentDidUpdate means that geocoder will not render on initial load

First off, useful thing that you made. Thanks!

I'm attempting to add geocoder functionality to our map component for Civic (https://github.com/hackoregon/civic), and decided to give using your package a try.

I was able to get it working, but the geocoder won't render on initial load until after you interact with the map.

Looking at your code, you are using componentDidUpdate to check for the presence and render the geocoder. This means that the geocoder will only appear after component updates, not on initial load. A quick fix would be to call the same code in componentDidMount.

Here's my code:
https://github.com/hackoregon/civic/pull/363/files#diff-d00726a23a264cadbb4187a041e71c16

Let me know if you have questions!

Add documentation for props and getGeocoder method to README

As a user, I don't want to have to look at the source code to know that you can pass Mapbox Geocoder options as a prop and that there's a method to get access to the Mapbox Geocoder instance. It would also be nice to have a link directly to the Mapbox Geocoder docs.

Add inputValue prop

Allow users to pass in an inputValue prop which will give them the ability to set the input value.

422 error: Query too long - 21/20 tokens

Some of my users are experiencing 422 errors in production.

Here is an example of log received through Sentry.io :

{
  "body": {
    "message": "Query too long - 21/20 tokens"
  },
  "type": "HttpError",
  "message": "Query too long - 21/20 tokens",
  "request": {
    "body": null,
    "origin": "https://api.mapbox.com",
    "file": null,
    "_options": {
      "path": "/geocoding/v5/:mode/:query.json",
      "params": "[Object]",
      "method": "GET",
      "query": "[Object]"
    },
    "response": null,
    "id": 15,
    "headers": {},
    "client": {
      "origin": "https://api.mapbox.com",
      "accessToken": "[FILTERED]"
    },
    "params": {
      "query": "jade & Spa, Calle 55 Supermanzana II, Manzana 4 Lote I-0I, Puerto Morelos Benito Juárez, Puerto Morelos, Quintana Roo 77580, Mexic",
      "mode": "mapbox.places"
    },
    "aborted": false,
    "error": "[Circular ~]",
    "path": "/geocoding/v5/:mode/:query.json",
    "method": "GET",
    "query": {
      "country": "[undefined]",
      "proximity": "[Array]",
      "limit": 5,
      "language": "[Array]"
    },
    "emitter": {
      "_events": "[Object]",
      "_eventsCount": 0
    },
    "sent": true
  },
  "statusCode": 422
}

As seen in Mapbox documentation, we may have to filter words in query so it never sends more than 20 words: https://docs.mapbox.com/api/search/#geocoding-api-errors

Let me know if you have the same issue and if I can do anything.

Thanks

window is not defined

I'm not able to load the plugin at all via pnpm.

window is not defined
ReferenceError: window is not defined
    at Object.<anonymous> (../..//node_modules/.registry.npmjs.org/suggestions/1.6.0/node_modules/suggestions/index.js:57:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/./..//node_modules/.registry.npmjs.org/@mapbox/mapbox-gl-geocoder/4.1.2/node_modules/@mapbox/mapbox-gl-geocoder/lib/index.js:3:17)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)

Cursor interacts with map through the geocoder control

When hovering the cursor over the geocoder control, clicking and dragging with the cursor moves the map below. The map also zooms when double-clicking over the search bar (see below). This can cause issue when drag-selecting the string in the control.

The issue is replicated in the demo in this repo (https://codesandbox.io/s/l7p179qr6m).

Does anyone have a workaround for this? I've tried modifying the z-index so far with no luck.

64724987-340f1800-d499-11e9-94a7-d48de099ba7f

Thanks @SamSamskies for this great library!

Need some help

<DeckGL
  ref={this.deckGl}
  layers={renderLayers({
    gridData,
    gridDataMax,
    selectedData,
    radiusSelection,
    layers,
    zoom: Math.trunc(viewState.zoom),
    onClick: (click, ev) => this.onClick(click, ev),
    poiOnClick: e => this.poiOnClick(e),
    layerSettings,
    colorRange,
  })}
  initialViewState={{ ...viewState, dragRotate: false, pitchWithRotate: false, doubleClickZoom: false }}
  onWebGLInitialized={this.onInitialized}
  onViewStateChange={this.onViewStateChange}
  onDragEnd={this.onDragEnd}
  controller={controller}
  getCursor={() => 'pointer'}
>
  <StaticMap
    ref={ref => { this.staticMap = ref && ref.getMap() }}
    reuseMaps
    mapStyle={this.state.mapStyle}
    preventStyleDiffing
    mapboxApiAccessToken={MAPBOX_TOKEN}
    onLoad={this.onLoadStaticMap}
  >
    {popup.clickedObject && selectedDataOnSameZoomLevel && (
      <Popup
        longitude={popup.x}
        latitude={popup.y}
        closeButton={false}
      >
        <div className={compareView ? 'split-view' : ''}>
          {compareView &&
            ((mapKey === 'mainMap') ? <span className="viewId viewIdMain">View 1</span> : <span className="viewId viewIdSecondary">View 2</span>)
          }
          <strong>{popup.label}</strong><br />
          {
            zoomLevel >= 13 &&
            (<span className="location-capitalize">{popup.location}</span>)
          }
        </div>
      </Popup>
    )}
    {layers.layersPopup && zoomLevel >= 13 && (
      <Popup
        className='popup-poi'
        longitude={layers.layersPopup.x}
        latitude={layers.layersPopup.y}
        onClose={this.poiOnClose}
      >
        <div>
          <h3 className="title">{layers.layersPopup.title}</h3>
          <p className="category">{layers.layersPopup.category}</p>
        </div>
      </Popup>
    )}
  </StaticMap>
  <Geocoder
    mapRef={this.deckGl}
    onViewportChange={this.onViewStateChange}
    mapboxApiAccessToken={MAPBOX_TOKEN}
  />
</DeckGL>

For my example code above, I cannot use <Geocoder> component inside <DeckGL>. I got this error.
Screen Shot 2562-08-09 at 17 43 27
@SamSamskies please help me for this, thanks 😄

Update README

Demo section

  • include demo that is a functional component and uses hooks
  • include code that demos how to ignore map events in the linked Code Sandboxes

Example code displayed

  • switch to a functional component that uses hooks.
  • includes code that demos how to ignore map events

Filtering suggestions further to trim results to a city

This is probably a noob question on my part so apologies in advance.
I am currently trying to add geo-filtering to my map to lock things down to a city but search suggestions still show areas outside the target zone which tells me I'm probably doing something wrong.

Here's my code:

    <MapGL
        ref={this.mapRef}
        {...viewport}
        onViewportChange={this.handleViewportChange}
        mapboxApiAccessToken={MAPBOX_TOKEN}
    >
      <Geocoder
          mapRef={this.mapRef}
          onResult={this.handleOnResult}
          containerRef={this.geocoderContainerRef}
          onViewportChange={this.handleGeocoderViewportChange}
          mapboxApiAccessToken={MAPBOX_TOKEN}
          reverseGeocode={true}
          bbox={[-0.489,51.28,0.236,51.686]}
          filter={event => {
            // returns true if item contains New South Wales region
            return event.context.map( i => {
              return (i.id.split('.').shift() === 'place' && i.text === 'London');
            }).reduce(function (acc, cur) {
              return acc || cur;
            });;
          }}
      />
      <DeckGL {...viewport} layers={[searchResultLayer]} />
    </MapGL>

I guess the question here would be; what should go in the reduce function arguments?

Write tests

As a user, I'd be more confident in using this library if it was well tested.

Animation speed settings

Hi @SamSamskies,
I just integrated this into my project and noticed that the animation is very slow when updating location. Is there a way to change the settings to update this? Thanks for your hard work!

Geocoder not showing up on map

Thanks for making this! I've tried incorporating it into my Map component, but it's not showing up at all, for some reason. Here is my code:

import React, { Component } from 'react';
import 'mapbox-gl/dist/mapbox-gl.css';
import MapGL, { NavigationControl } from 'react-map-gl';
import Geocoder from 'react-map-gl-geocoder';

const token = process.env.REACT_APP_API_KEY;

class Map extends Component {
    constructor(props) {
        super(props);
        this.state = {
            viewport: {
                latitude: 35.9555072,
                longitude: -83.9901184,
                zoom: 12,
                width: 500,
                height: 500
            }
        };
    }

    mapRef = React.createRef()

    render() {
        const { viewport } = this.state;

        const updateViewport = (viewport) => {
            this.setState({ viewport })
        };

        return (
            <MapGL {...viewport} mapRef={this.mapRef} mapStyle='mapbox://styles/mapbox/streets-v9' mapboxApiAccessToken={token} onViewportChange={updateViewport}>
                <div className="nav">
                    <NavigationControl onViewportChange={updateViewport} />
                </div>
                <div className="geocoder">
                    <Geocoder mapRef={this.mapRef} onViewportChange={updateViewport} mapboxApiAccessToken={token} />
                </div>
            </MapGL>
        );

    }

}

export default Map;

I'm just not seeing any geocoder component appearing on my screen at all. Is there something I'm missing?

Can't resolve 'gl-mat4/invert'

i updated packages and now i get this error

Failed to compile.
./node_modules/react-map-gl-geocoder/node_modules/viewport-mercator-project/dist/esm/viewport.js
Module not found: Can't resolve 'gl-mat4/invert' in '...'

react: 16.8.1,
deck.gl: 6.4.1,
react-map-gl: 4.0.10,
react-map-gl-geocode": 1.6.3,

how to prevent submit from setting the viewport to the result coords?

Is there any way to prevent the map from zooming into the selected address? I'm trying to use the geocoder to basically just allow the user to type in an address, then setting the lat/lng into the state without actually moving the viewport there.

essentially i was to use this value from the state to filter my markers based of a proximity around result.result.center coords

handleGeocoderViewportChange = viewport => {
  const geocoderDefaultOverrides = { transitionDuration: 1000 };
  return this._onViewportChange({
    ...viewport,
    ...geocoderDefaultOverrides
  });
};

handleGeocoderResult = result => {
  this.setState({
    searchLngLat: result.result.center
  });
};

<Geocoder
  mapRef={this.mapRef}
  onViewportChange={this.handleGeocoderViewportChange}
  onResult={this.handleGeocoderResult}
  mapboxApiAccessToken={"***"}/>

Error during componentWillUnmount

I get an error when the map is unmount:

index.js:247 Uncaught TypeError: Cannot read property 'removeControl' of null
    at Geocoder._this.removeGeocoder (index.js:247)
    at Geocoder.componentWillUnmount (index.js:334)
    at callComponentWillUnmountWithTimer (react-dom.development.js:16816)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)

It seems to happen because the MapGL unmount first, so its ref becomes null, and then the Geocoder unmount after and try to use the ref in the removeGeocoder() function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.