In this lesson, you will learn how to add a Marker and Popup component to a Map when using React Leaflet. We'll walk you through importing the components and adding each one to the Map. Additionally, we'll resolve an issue with loading marker images that's inherent to creating a new React Leaflet map in Create React App, which we'll fix by manually importing the image from Leaflet and configuring those images to the marker.
Colby Fayock: [0:00] We're going to start off with a basic map zoomed in on Washington, DC. In our app, we have our Map component and our TyleLayer component which uses OpenStreetMap.
[0:07] Starting with our Marker, the first thing we want to do is import it from react-leaflet. Next, we want to add that Marker component inside of our Map. On that Marker component, we want to add a position prop, which we can use the same location as we did for our Map.
[0:18] If we hit Save and reload our map, we still don't see a Marker component. The reason for this is when we import our Leaflet CSS, we can't find the images in the app. To get around this, we're going to import Leaflet and fix this ourselves.
[0:28] First, we want to delete the getIconUrl prototype from the default Leaflet icon. Now, on that default icon, we can provide some additional settings. Inside mergeOptions, we want to provide an iconRetinaUrl, an iconUrl, and a shadowUrl.
[0:40] For the iconRetinaUrl, we want to require an image straight from Leaflet. Similarly, we want to require an image for the iconUrl and the shadowUrl. Once we hit Save and open up our browser, we can see our Marker.
[0:50] Next, to add the Popup component, we want to import it from react-leaflet. With it imported, we can add it to our Marker. Inside our Popup, we can add any message we want. Once we hit Save, we can open back up our browser, click our Marker and see our Popup.
[1:02] To review, we imported a Marker component and a Popup component from react-leaflet. We also added a fix to make our Marker show up properly. With our components imported, we added our Marker and our Popup to the Map. With the custom message, we can see our Marker and 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!