Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Leaflet Search Box Implementation

Are there any resources showing a search box implementation with react-leaflet?

I'd like to have my map pins populate upon a search result that would query and retrieve my existing data.

ie:

const names = [

  {name: 'Joe', location: '40.734621, -73.989341 '},
  {name: 'Seth', location: '45.77621, -73.789654 '},

]

Then, after searching for Joe or Seth, the map would populate with the location coordinates.

I found examples for leaflet.js but couldn't find any examples spun with react-leaflet.

like image 575
Null isTrue Avatar asked Jan 16 '18 22:01

Null isTrue


2 Answers

Take a look at leaflet-geosearch

Install it with npm install --save leaflet-geosearch

Then you just need to build a component with it:

import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch';

class Search extends MapControl {

  createLeafletElement() {
    return GeoSearchControl({
      provider: new OpenStreetMapProvider(),
      style: 'bar',
      showMarker: true,
      showPopup: false,
      autoClose: true,
      retainZoomLevel: false,
      animateZoom: true,
      keepResult: false,
      searchLabel: 'search'
    });
  }
}

export default Search;

And use your component in your Map:

render() {
  return (
    <Map>
      (...)
      <Search />
    </Map>
  );
}
like image 199
Rodius Avatar answered Sep 28 '22 00:09

Rodius


I think I found a much easier way of doing this without needing to create and extend a class.

import { Map, useLeaflet } from 'react-leaflet'
import { OpenStreetMapProvider, GeoSearchControl } from 'leaflet-geosearch'

// make new leaflet element
const Search = (props) => {
    const { map } = useLeaflet() // access to leaflet map
    const { provider } = props

    useEffect(() => {
        const searchControl = new GeoSearchControl({
            provider,
        })

        map.addControl(searchControl) // this is how you add a control in vanilla leaflet
        return () => map.removeControl(searchControl)
    }, [props])

    return null // don't want anything to show up from this comp
}


export default function Map() {
  return (
    <Map {...otherProps}>
      {...otherChildren}
      <Search provider={new OpenStreetMapProvider()} />
    </Map>

  )
}
like image 24
Taylor Austin Avatar answered Sep 28 '22 00:09

Taylor Austin