问题
Based on: Dim/Hide rest of map around country with leaflet.js
While the accepted answer was almost spot on, its JSFiddle demo only works for old single polygon GeoJSON. Modern multipolygon GeoJSON allows for additional shapes to make up for overseas territories etc., and thus also introduces extra arrays which the JSFiddle demo doesn't know how to handle:
// transform geojson coordinates into an array of L.LatLng
var coordinates = france.features[0].geometry.coordinates[0];
var latLngs = [];
for (i=0; i<coordinates.length; i++) {
latLngs.push(new L.LatLng(coordinates[i][1], coordinates[i][0]));
}
L.mask(latLngs).addTo(map);
I realize this is all basic JavaScript and array 101 stuff, but would anyone happen to know how to make the above code work with the additional arrays from multipolygonal GeoJSON?
- Multipolygon example from https://geojson-maps.ash.ms/: https://jsfiddle.net/uc81esy5/
- Single polygon example used in the accepted answer: https://jsfiddle.net/r9m4t3d7/
回答1:
I guess that by "modern GeoJSON" you mean "GeoJSON features of type Polygon with an outer ring but also with inner rings". So this is really about "How do I convert a GeoJSON multipolygon geometry to an array (rings) of arrays (points in a ring) of arrays (Leaflet LatLng
s)?".
Please note that the concept of polygons with inner rings is by no means "modern": it does appear in the (now deprecated) 2008 GeoJSON specs, which in turn take heavy inspiration from OGC's Simple Features which date back to 2003.
I would leverage the coordsToLatLngs static method of L.GeoJSON already implemented by Leaflet. e.g.:
var latlngs = L.GeoJSON.coordsToLatLngs(feature.geometry.coordinates, 1);
Remember to perform a sanity check on geometry.type
if neccesary; the levelsDeep
parameter shall be 0 for LineString
s, 1 for MultiLineString
s and Polygon
s, and 2 for MultiPolygon
s.
来源:https://stackoverflow.com/questions/61900784/leaflet-js-only-show-specific-countries-dim-or-hide-the-rest