Home > Blockchain >  Bounds are not valid error calling fitBounds
Bounds are not valid error calling fitBounds

Time:07-28

I have Nominatim GeoJSON data representing a country's border such as this https://nominatim.openstreetmap.org/search?country=it&polygon_geojson=1&format=json and getting it through ajax. I'm using Leaflet to create and display the map.

After calling geoJson(jsonData) I want the map to fit this border with fitBounds() but I get Uncaught Error: Bounds are not valid..

This is my code:

$.ajax({ url: NOMINATIM_BOUNDARY_URL })
.done( function(json) {
  console.log(json); // the json is loaded correctly.
  var layer = L.geoJson(json);
  console.log(layer.getBounds()); // this prints 'undefined'. Why?
  mapref.fitBounds(layer.getBounds()); // mapref is our map object.
});

I think I'm getting the error because bounds are undefined. Why?

Thanks.

CodePudding user response:

I solved my problem thanks to IvanSanchez's suggestion in the comments.

The problem was that the Nominatim object had some other stuff besides the GeoJSON, so I just had to inspect the object and used what I needed, namely json[0].geoJson.

My code then becomes:

$.ajax({ url: NOMINATIM_BOUNDARY_URL })
.done( function(json) {
  var layer = L.geoJson(json[0].geoJson);
  console.log(layer.getBounds()); // this doesn't print 'undefined' anymore.
  mapref.fitBounds(layer.getBounds()); // now this works!
});
  • Related