Search code examples
openlayersgis

how to adjust center and zoom level according to the geojson in openlayers 2


When we display the GeoJson, it is perfectly positioned and zoomed just like in Leaflet(e.g. http://www.geojsonlint.com/) How to do the same in OpenLayers2?


Solution

  • You get the bounds from the feature's geometry (ie, what is returned by the GeoJSON format reader), and then call map.zoomToExtents(bounds, closest). The closest parameter determines how closely it zooms to the extents of the polygon.

    var geojson_format = new OpenLayers.Format.GeoJSON();
    var vectors = new OpenLayers.Layer.Vector();     
    map.addLayer(vectors);  
    var feature=geojson_format.read(json); 
    vectors.addFeatures(feature);    
    var bounds=feature[0].geometry.getBounds();
    map.zoomToExtent(bounds, false);
    

    Here is a jsFiddle showing it in action.