Manage Map Data and Feature Shapes Together in a React Leaflet LayerGroup or FeatureGroup

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 the LayerGroup and FeatureGroup components to organize feature shapes on our map. Using these grouping features, we'll learn how the LayerGroup is used for organizational purposes like adding or removing multiple layers at once and how we can update the color of all of our grouped shapes with the color prop on our FeatureGroup.

Colby Fayock: [0:00] We're going to start off with a map zoomed in on Washington, DC. On that map we have some circles identifying some of the monuments and the White House. Inside our code, we're importing a Map, TileLayer, and Circle from 'react-leaflet'.

[0:12] We're setting our defaultCenter and our defaultZoom as well as the coordinates of our different features. With these components and coordinates, we're creating a Map, TileLayer, and Circles with the features.

[0:22] Leaflet gives us tools to separate group shapes. How can we do that? First, let's import the LayerGroup from 'react-leaflet'. Then we can add our LayerGroup component to our map. With that LayerGroup, let's nest two of our features inside that group.

[0:39] If we reload the map, we can see it doesn't really do anything. LayerGroups are often used for adding and removing multiple layers at once. What if we wanted to change the color of a few of them at once?

[0:48] To do that, we want to import a FeatureGroup from 'react-leaflet'. To do that, we want to add our FeatureGroup to our map, then send it to the LayerGroup. We want to nest our components inside that group. If we reload the page, we still can't see anything, but now we can set our color to blueviolet. If we reload the map, our FeatureGroup layers are now purple.

[1:10] In review, we imported a LayerGroup and a FeatureGroup from 'react-leaflet'. With those groups, we grouped our layers into two separate groups. Since the LayerGroup is more for organizational purposes, we couldn't really do anything with it.

[1:21] On our FeatureGroup, we set a new color and saw the group players on our map.