1. 59
    Use the Browser's Location to Add a React Leaflet Marker to the Map
    54s

Use the Browser's Location to Add a React Leaflet Marker to the Map

Colby Fayock
InstructorColby Fayock
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

While we were able to find our location, Leaflet's geolocation features don't set a marker by default. What they do provide is event handlers that allow us to know when the location is found.

Click here for exercise instructions

Colby Fayock: [0:00] When we use the Find My Location feature, it finds our location, but it doesn't add any marker to designate where it is. Leaflet doesn't have an option to do that by default. Instead, we can set up an event handler to listen to that locate function.

[0:11] That way, as soon as it locates something, it's going to fire a function for us. I already set up this new useEffect instance. Similar to when we were adding the markers, we're going to grab that map instance, and we're going to return if we don't find it.

[0:22] To listen for those location events, we're going to specify our map. We're going to say onLocationFound. We're going to specify a new function called handleOnLocationFound. Below that useEffect, we're going to define our new function.

[0:33] Similar to before, we're going to again destructure our map. This time, this handler passes an argument called event. We can use this to grab the lat and long value. Then just like before, we can create a new marker constant set that equal to a new Leaflet marker and pass in that lat long.

[0:47] With our marker, we can add it to our map. Now, next time we click Find My Location, we can see that as a marker for our location.