1. 7
    Create a New Map in React Leaflet using the Components TileLayer and Map
    1m 2s

Create a New Map in React Leaflet using the Components TileLayer and Map

Colby Fayock
InstructorColby Fayock
Share this video with your friends

Social Share Links

Send Tweet

The first thing we need to do is actually add our map. We already installed our dependencies, so now it's a matter of using them to import our components.

There are 2 primary components that we'll need to use:

  • Map
  • TileLayer

We'll import these components from React Leaflet and use them to create our map.

Click here for exercise instructions

Colby Fayock: [0:00] In order to add a map to our page, we need the components. We're going to import our map and a TileLayer from react-leaflet. Next, we don't need this header anymore, so we can replace it with a map component. At this point, if we reload the page, we can see that it's trying to do something, but it's not quite working yet.

[0:14] We can start to configure our map by adding a center prop where we're going to paste in these coordinates, which is in the center of DC. Mostly, going to set a zoom prop of 12, which tells leaflet how far to zoom into the map.

[0:23] Next, we need a TileLayer component to actually add the imagery to the map. We're going to add the TileLayer component, and I'm going to first set a URL prop, which for our TileLayer, we're going to use OpenStreetMap. Then I'm going to set an attribution prop, so I can give credit to the OpenStreetMap service.

[0:36] At this point, we can start to see our map, but it doesn't look quite right. In order to get our map to load right, we need to also import the leaflet-css. We're going to import the file directly from leaflet.

[0:45] Now, if we reload the page, it's actually gone. When we put our CSS in there, it's making the map work, but we need to add a fixed height to make it actually fill the container. Inside our app.css, we're going to add a new rule for leaflet container. We're going to specify a width of 100% and also a height of 100%. Now, if we reload the page, we can actually see our map.