We now have the power of the Leaflet API to make changes to our Map instance. With this, we can recreate our Marker component by tapping directly into the Leaflet API and creating a new Leaflet Marker instance.
We'll walk through accessing our Map instance from the ref in our useEffect hook and using it to recreate our marker on the map.
Colby Fayock: [0:00] In order to make use of our mapRef, we can first de-structure out our current property. Inside of our map instance, we're going to actually want to use the Leaflet element, which will let us interact with the map. We can also de-structure this Leaflet element from current, as well as rename it to map to make it easier to use.
[0:12] The first thing we want to do is if we don't actually have a map, we want to actually return out. That way, we don't try to run Leaflet code and get an error if it doesn't exist.
[0:19] Next, we can get started with creating markers. We're going to create a new constant called marker, which we're going to set equal to a new marker instance from Leaflet. Here, we'll copy and paste that same latitude and longitude that we use before right into our Leaflet marker.
[0:29] If we comment out our marker component to see if it works, we can see that we don't see anything on the map yet. We actually haven't added this marker to the map. What we can do is say, "Marker add to and then pass in map," and now we can see our marker. If you try clicking it, we're missing our popup.
[0:42] To get back our popup, we're going to say, "Marker bind popup." We can copy and paste that same title as before right into that function. If we go back to our map and click our marker, we can now see our popup.
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
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!