如何在单张中显示和居中单个国家多边形?
我在使用传单加载页面时尝试自动缩放到特定的国家/地区名称。 当我发布我的页面时,我可以得到一个变量,如:
var $myCountry = "France";
现在我加载我的json像:
$json = file_get_contents("/world.json"); $data = json_decode($json, true);
这是我的geoJson结构:
{ "type":"Feature", "id":"AFG", "properties":{"name":"France"}, "geometry":{ "type":"Polygon", "coordinates":[ [ [61.210817,35.650072], [62.230651,35.270664] ] } },
基本上我想检查我的变量名是否等于geoJson中的名称,如果是这样,我想得到它的坐标,沿着那些线。
var $myCoordinates = $myCountry.coordinates
我想这样做是为了根据变量中找到的国家名称放大到地图,我还检查了其他SO问题,但我没有得到它。
UPDATE
这几乎可行,变量和专有名称之间的比较不是tho,但变量字符串是正确的,并且通过json,我们确实有一个具有相同字符串的名称
var $country = ""; $.ajax({ type: 'GET', url: '/world.json', data: { get_param: 'value' }, dataType: 'json', success: function (data) { $.each(data, function(index, element) { if (element.properties.name == $country) { alert("ciao"); } }); } });
我认为我们最初显示您的代码和数据结构以及post标题时会被误导。
实际上,您并不是在尝试扫描数组或简单的JSON对象,而是使用具有FeatureCollection和许多function的GeoJSON对象。
因此,您必须遍历该FeatureCollection的function,并扫描每个function的properties.name
。
但即便如此,您仍然无法实现缩放到相应Leaflet图层的目标:GeoJSON对象未链接到您的Leaflet图层,反之亦然。
因此,您应该使用GeoJSON数据构建Leaflet GeoJSON组 ,然后扫描该组(例如,使用eachLayer()
)以找到具有properties.name === "France"
的Feature的表示层。
有点符合:
$.getJSON('/world.json', function (geoJSONdata) { var geoJSONgroup = L.geoJSON(geoJSONdata).addTo(map); geoJSONgroup.eachLayer(function (layer) { if (layer.feature.properties.name === "France") { // Zoom to that layer. map.fitBounds(layer.getBounds()); } }); });
演示: https : //plnkr.co/edit/SVJfLf8gR0VysrFVkwsS?p=preview