Leaflet.js: Only show specific countries, dim or hide the rest

偶尔善良 提交于 2020-06-17 15:46:13

问题


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 LatLngs)?".

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 LineStrings, 1 for MultiLineStrings and Polygons, and 2 for MultiPolygons.



来源:https://stackoverflow.com/questions/61900784/leaflet-js-only-show-specific-countries-dim-or-hide-the-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!