rob.m
rob.m

Reputation: 10571

How to auto zoom to a polygon in leaflet?

I have my geoJson format like this:

statesData.features.push({  
   "type":"Feature",
   "id":"AFG",
   "properties":{  
      "name":"Afghanistan"
   },
   "geometry":{  
      "type":"Polygon",
      "coordinates":[  
         [  
            [  
               61.210817,
               35.650072
            ],
            [  
               62.230651,
               35.270664
            ],
            [  
               62.984662,
               35.404041
            ],

I am trying to read those coordinates and set them as

        var coord = statesData.features[0].geometry.coordinates;
        lalo = L.GeoJSON.coordsToLatLng(coord);
        map.setView(lalo, 18);

The documentation says:

coordsToLatLng( coords ) Function that will be used for converting GeoJSON coordinates to LatLng points (if not specified, coords will be assumed to be WGS84 — standard [longitude, latitude] values in degrees).

But I am getting this error in console

Uncaught Error: Invalid LatLng object: (undefined, 61.210817,35.650072,62.230651,35.270664,62.984662,35.404041...

UPDATE

The first answer is correct as it solves the issue above, however, it zooms the map to the first set of coordinates while what I am really trying to achieve is to be able to load the page with the map auto zoomed to a polygon (I only load one polygon).

This example is the closest i could find

Upvotes: 3

Views: 12534

Answers (2)

You are passing an array of arrays of arrays as a parameter. coordsToLatLng doesn't expect that. It only expects one array, being it the coordinates: https://www.dartdocs.org/documentation/leaflet/0.0.1-beta.1/leaflet.layer/GeoJSON/coordsToLatLng.html

So your code has to be actually:

var coord = statesData.features[0].geometry.coordinates[0][0];
lalo = L.GeoJSON.coordsToLatLng(coord);
map.setView(lalo, 18);

This will get the coordinates of your first point inside your double-array. Btw, I'm pretty sure that double-array is not what you really want.

Upvotes: 1

rob.m
rob.m

Reputation: 10571

Thanks to the answer I got from here the solution is to use leaflet layerGroup.

Following leaflet example as that is what I am using, based on their code and the other answer i got, this is what worked for me. The php bit is what I use to get the country name I need as per my project. The following gets a name, compares it if there is a name in the geoJson like that and if so, centers and zooms the map to that polygon:

geojson = L.geoJson(statesData, {
  style: style,
  onEachFeature: onEachFeature
}).addTo(map);

<?php 
    $myCountry = usp_get_meta(false, 'usp-custom-3');
    $fixedname = ucfirst($myCountry); 
?>

geojson.eachLayer(function (layer) {
  if (layer.feature.properties.name === "<?php echo $fixedname; ?>") {
    // Zoom to that layer.
    map.fitBounds(layer.getBounds());
  }
});

Upvotes: 3

Related Questions