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.

egghead
egghead
~ 33 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today