How to show and center a single country polygon in

2019-09-07 09:40发布

问题:

I am trying to auto zoom to a specific country name when I load the page using leaflet. When I post my page, i can get a variable like:

var $myCountry = "France";

Now I load my json like:

$json = file_get_contents("/world.json");
$data = json_decode($json, true);

This is my geoJson structure:

{
  "type":"Feature",
  "id":"AFG",
  "properties":{"name":"France"},
  "geometry":{
    "type":"Polygon",
    "coordinates":[
      [
        [61.210817,35.650072],
        [62.230651,35.270664]
      ]
  }
},

Basically I want to check if my variable name is equal to a name within the geoJson and if so I want to get the coordinates of it, something along those lines.

var $myCoordinates = $myCountry.coordinates

I want to do this in order to zoom in to a map based on the country name found in the variable, I have also checked this other SO question but I didn't get it.

UPDATE

This almost works, the comparison between the variable and the propriety name isn't tho, yet the variable string is correct and wihtin the json we do have a name with the same string

var $country = "<?php echo $region; ?>";

$.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");
        }
    });
    }
});

回答1:

I think we were misled by how you initially showed your code and data structure, and your post title.

Actually you are not trying to scan an array or a simple JSON object, but a GeoJSON object with a FeatureCollection and lots of Features.

So you have to loop through that FeatureCollection's Feature, and scan each Feature's properties.name.

But even with that, you will still not be able to perform your objective of zooming onto the corresponding Leaflet layer: the GeoJSON object is not linked to your Leaflet layers, whereas the reverse is.

So you should instead build the Leaflet GeoJSON group out of your GeoJSON data, and then scan that group (e.g. using eachLayer()) to find the layer that is the representation of a Feature with properties.name === "France".

Something in line of:

$.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());
      }
    });
});

Demo: https://plnkr.co/edit/SVJfLf8gR0VysrFVkwsS?p=preview