Add Placename Location Search to React Leaflet with Esri Leaflet Geocoder

Colby Fayock
InstructorColby Fayock
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we'll use the Esri Leaflet Geocoder plugin to add placename search on a React Leaflet map. We'll walk through installing the plugin with yarn or npm, importing the geosearch function from the plugin, and using it to add a new search control to the map. Once added, we'll also set up an event handler to fire custom code with the results data whenever a search is made.

Esri Leaflet Geocoder

Colby Fayock: [0:00] We're going to start off with a map in the center of the world. The world's a big place. If we want to find a specific location, we have to do so pretty manually. Instead, we're going to use a plugin called Esri Leaflet Geocoder. This plugin provides ArcGIS Online geocoding services for placename search on a map.

[0:15] To get started, we're going to install esri-leaflet-geocoder with yarn or npm. Once installed, we can start back up our server. In our code, we're going to start off by importing Map and TileLayer from 'react-leaflet'. We're using that Map and TileLayer component to create our app. We're also using the React Hooks useEffect and useRef in order to create a mapRef which lets us access our current map.

[0:34] To get started, we're going to import { geosearch } from 'esri-leaflet-geocoder'. With that imported, we're going to create a new constant called control, and then set that = geosearch. With that created, we can take our control and add it to our map.

[0:47] If we reload our map, we can see a new control, but it doesn't quite look right. We're going to also import the CSS file from the package. Once we reload the page, we can search for whatever we want. If we wanted to do something more advanced, we can set up a custom event handler to fire custom code when the results load.

[1:02] To do this, we're going to set up an event handler on our control to listen for results. Then we'll create a function called handleOnSearchResults(), which will receive an argument of data, which we can console.log to test it out. With our new function, we can set it to fire on results.

[1:16] The last thing you might want to do is clean up that event handler. Inside useEffect, you can return. When the component unmounts, you can turn off our results with that function. The next time we do a search, we can see all the data from our search results.

[1:29] In review, we installed the esri-leaflet-geocoder. With that installed, we imported the geosearch function. We used that to create a search control and added to the map. We even set an event handler to listen for the results. After importing the CSS to fix the styles, we added a placename search to our map.