Use Leaflet's Geolocation API to Find a Browser's Location to Update a React Leaflet Map

Colby Fayock
InstructorColby Fayock

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

In this lesson, we'll use Leaflet's map locate method to use the browser's API to find the visitor's current location and update the React Leaflet map to that location. We'll walk through what the locate method does, set an event handler to trigger when it locates, and use the accuracy and location data to add a circle to the map designating the area.

Colby Fayock: [0:00] We're going to start off with a basic map centered in the middle of the world. In our code, we're importing a Map and a TileLayer from 'react-leaflet'. We're using those Map and TileLayer components to create our app. We're also creating a mapRef using the useRef hook. That way, we can grab the leafletElement from the mapRef.

[0:15] To get started finding the location, we can use the locate() method on the map. By default, if we open up this page, now we can see it's asking permission to locate it. If we click allow, it still doesn't really do anything.

[0:25] If we want to update the location on the map, we can pass an options object and use the setView key and set it to true. If we reload our map and allow it to find our location again, it updates our map to the location.

[0:36] If you notice though, it doesn't give any indication on the accuracy of the location. Luckily, Leaflet lets us send an event handler to grab some more information.

[0:43] Let's create a new function called handleOnLocationFound(). With this function, we'll receive an event argument. Then we can grab the latlng from the event.latlng and then the radius from the event.accuracy property.

[0:58] To create a new circle, we'll need to import Leaflet. Let's import L from 'leaflet', where we then create a new circle. In that circle, we'll use the latlng and the radius.

[1:09] Finally, we want to add that circle to our map. We can use our previous destructure statements and copy and paste that into our event. Then, we can take the circle and add it to the map.

[1:18] Lastly, in order for our map to use that event, we want to create an event handler for our map, use locationfound and then pass in our function for the handler. Finally, if we load back up our map and click allow, we can see the circle on the map that designates the accuracy radius.

[1:33] In review, we use the locate method on the map to set the new view using our location. Once Leaflet found our location, we can set up an event handler that passes us details like the latlng and the radius where we could create a circle to represent that then add it to the map, which allowed us to get the location and add a circle to the map.