In this lesson, you will learn how to add GeoJSON data to a map in React Leaflet. Using the National Parks in the United States, we'll import a GeoJSON document, create a new Leaflet GeoJSON instance, and add a marker with a popup for each park.
Colby Fayock: [0:00] We're going to start off with a basic map over the United States. We're importing the Map and the TileLayer from 'react-leaflet'. Then we're using those components in our App.
[0:09] To fix an issue with the markers, we're deleting the default icon and remerging it with options from the Leaflet package. Additionally, so we can utilize the Leaflet Map API, we're using a useEffect Hook, as well as the mapRef on our map.
[0:22] In order to add data to our map, we need data, so I found a GeoJSON document that has all the national parks in the United States. Luckily, I was able to find this on the nps.gov website. Here they're using that data for their own map demo.
[0:35] To start using that data, the first thing we want to do is import it. We're going to import nationalParks from our JSON file. With our new data, we want to add it to the map. Let's create a constant called parksGeoJson. Start a new instance of Leaflet GeoJSON and use our data. With that parksGeoJson we can add it to the map. When we check out our map, we can see all the markers across the United States.
[1:01] To take this further, what if we clicked it and it showed the name? To do this, we want to set a custom configuration on the Leaflet GeoJSON. We're going to use a property called onEachFeature, create a new function. We get arguments of feature, which will default to an object, and layer.
[1:17] Inside that function let's first destructure our properties, set the default as an empty object, which comes from feature. We can also destructure the Name, which comes from properties. If we don't have a Name, let's first return. If we do have a Name, let's bind a popup to our layer. Inside that popup we want to create a paragraph tag. Inside that paragraph, we can add our Name.
[1:40] Once you hit Save, going back to our map, and click one of the markers, you see the name.
[1:44] To review, we grabbed the data of all the national parks of the United States. We first imported that data to our App. With that data, we created a new GeoJSON instance. For each layer on that instance, we binded a popup with its name. Finally, after adding it to the map, we can see our parks and our popups on the map.