1. 57
    Add a React Leaflet Marker to a Location when Clicking a Button
    43s

Add a React Leaflet Marker to a Location when Clicking a Button

Colby Fayock
InstructorColby Fayock
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Most of us are able to identify where we're located on the map, but it can be hard to visualize that in context to other locations. To help, we can add a marker to the map to show our location.

To get started, we'll add a marker to a specific location to see how it relates to the restaurants that are on our map.

Click here for exercise instructions

Colby Fayock: [0:00] In order to add a marker onClick, I already set up this button with an event handler. Here, when someone clicks button, we fire handleOnSetLocation, which right now, we're only defining a location.

[0:09] To add a marker, we can do what we did in previous exercises. We're going to create a const marker. We're going set that equal to a Leaflet marker. We're going to pass in our location of ('National Geographic').

[0:20] Since we already have our Leaflet map de-structured, we can specify that our marker will get added to our map. When we go back and click the button, we can see our marker. What if we're zoomed in on Foggy Bottom, and we click that button? Well, we can see that our marker was added. It's not centered in the map.

[0:34] After we add our marker, we can tell our map to set it to view to that same location. Next time we're not zoomed in on that location when we click the button, it's going to update its location to our marker.