How to use maps as location input in react?

2.8k views Asked by At

I am trying to make a form that a user can search their location or pin his location. I am using react-leaflet for loading a map and react-leaflet-search for adding the search functionality. The search functionality is working fine. Below you can see the code.

<Map center={position} zoom={zoom}  onDragEnd = {function(e){ console.log(e);}} >
  <TileLayer
    attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'/>
  <Search 
    position="topright" 
    showPopup={false} 
    provider="OpenStreetMap" 
    showMarker={true} 
    openSearchOnLoad={true} 
    closeResultsOnClick={true} 
    providerOptions={{ region: "np" }}/>
</Map>

What I want to do is to access user's entered location or latitude longitude of the marker that is displayed after user selects the location. I tried to search for event listeners, but could not find any. Currently I am trying to use onDragEnd event but I have not succeeded yet. Could anyone tell me how to achieve what I am trying to do?

1

There are 1 answers

5
Christos Lytras On BEST ANSWER

Unfortunately react-leaflet-search has not a proper way to retrieve search results. There is mapStateModifier callback that we can use to get the search result coordinates LatLng object, but we'll have to setup the map flyTo call as well:

render() {
  const position = [51.505, -0.09];
  const zoom = 13;

  return (
    <div>
      <Map 
        ref={ref => this.mapRef = ref}
        center={position} 
        zoom={zoom}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='https://{s}.tile.osm.org/{z}/{x}/{y}.png' />

        <ReactLeafletSearch 
          ref={ref => this.mapSearchRef = ref}
          mapStateModifier={(latLng) => {

            // Do work with result latitude, longitude
            console.log('Search Latitude:', latLng.lat);
            console.log('Search Longitude:', latLng.lng);

            if (this.mapRef) {
              // Because we have a custom mapStateModifier callback,
              // search component won't flyTo coordinates
              // so we need to do it using our refs
              this.mapRef.contextValue.map.flyTo(
                latLng,
                this.mapSearchRef.props.zoom,
                this.mapSearchRef.props.zoomPanOptions
              );
            }
          }}
          position="topright" 
          showPopup={false} 
          provider="OpenStreetMap" 
          showMarker={true} 
          openSearchOnLoad={true} 
          closeResultsOnClick={true} 
          providerOptions={{ region: "np" }}
        />
      </Map>
    </div>
  );
}

You can check this example Stackblitz to see it working.