Customize GeoJSON Data Markers with a React Leaflet Icon Image

Colby Fayock
InstructorColby Fayock

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson, we'll use an image to create a custom map marker icon for GeoJSON location data on our map. We'll walk through importing a custom image, creating a new Leaflet Icon and Marker instance, and use them to customize our National Parks markers.

Colby Fayock: [0:00] We're going to start off with a map of the United States. On that map we have markers for each national park in the United States. In our app, we're importing a Map and a TileLayer from 'react-leaflet', and we're adding them as components to our app.

[0:12] To fix an import issue with markers, we're first deleting the _getIconUrl from the Icon.Default and reconfiguring that icon with images from the Leaflet package. To add our map data to the map, we're creating new GeoJSON instance with the nationalParks data, and also binding a popup with its name.

[0:28] In order to add a custom marker to our map, we need a custom image. I created this map marker with a green background and a tree. The first thing we want to do is import our treeMarker from the source. Once we had that, we're going to create a new parkIcon. We're going to set it to a new L.Icon() instance.

[0:46] Configure its settings and we can set our iconUrl to treeMarker. Here we want to add the pointToLayer property. We create a new function. That function will have arguments of feature and latlng.

[0:59] In that function we want to return a L.marker. The first argument will be the latlng and the second will be a configuration object where we'll set our icon to parkIcon. If we look at our map, the icons are way too big. We can set our iconSize to 26 by 26. That's looking better.

[1:18] If we click one of the icons, the popup's still not aligned quite properly. We can set up popupAnchor and move it up 15 pixels. If we check out our markers again, that's much better.

[1:30] If you notice, we used to have shadows be at our markers. How can we get that back? Using the same shadows from Leaflet, we can import our markerShadow from the leaflet source. On our parkIcon we can set the shadowUrl to our markerShadow.

[1:44] Similar to our markers, these aren't quite aligned. As positioned properly, we can set our shadowAnchor to 13 by 28. If we look back at our map, we can see all of our markers with the shadows.

[1:55] To review, we imported our treeMarker and our markerShadow images. Using those images, we created a new Leaflet icon called parkIcon. On our GeoJSON instance, we added the pointToLayer property where we returned a Leaflet marker with our park icon which created a new marker icon for each park on our map.