Create and draw a GeoJSON polygon hole as with Leaflet
In our previous code sample, we showed how to add a geoJSON polygon to a Leaflet map. In this example, we would like to show how to draw the polygon as a hole of the map cover polygon. The full version of the code sample you can find on JSFiddle.
1. Get the top-level polygons from an Isoline API polygon
The Isoline API can return multiple features as a result when multiple ranges (travel times) were requested. As we requested only one range (30 minutes) isoline, we can be sure that the first feature contains the result;
const holePolygons = geoJSONFeatures.features[0].geometry.coordinates.map(
(poly) => poly[0]
);
2. Generate the map cover polygon
const mapCover = [
[-179.99, 89.99],
[-179.99, 0],
[-179.99, -89.99],
[0, -89.99],
[179.99, -89.99],
[179.99, 0],
[179.99, 89.99],
[0, 89.99],
[-179.99, 89.99],
];
Note! As we work with GeoJSON, the coordinates have [Longutude, Latitude]
format.
3. Create a GeoJSON Polygon Feature and add it with L.geoJSON()
const geoJSONPolygon = {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [mapCover, ...holePolygons],
},
};
L.geoJSON(geoJSONPolygon, {
stroke: true,
color: "#000",
weight: 2,
opacity: 0.7,
fill: true,
fillColor: "#000",
fillOpacity: 0.3,
smoothFactor: 0.5,
interactive: false,
}).addTo(map);