[GIS] OpenLayers2 – zoom to selected feature

openlayers-2web-mappingzoom

If I have this vector layer:

var vectors = new OpenLayers.Layer.Vector("vector", {isBaseLayer: false});
var feature = new OpenLayers.Feature.Vector(
                OpenLayers.Geometry.fromWKT(
                    "POLYGON ((-18 -3, -18 14, 15 14, 15 -3, -18 -3))"
                )
            );
vectors.addFeatures([feature]);

How I can zoom to a selected feature of the layer by a single click event?

Best Answer

you can use it adding to any trigger:

var dataExtent = vectors.getDataExtent();
map.zoomToExtent(dataExtent);

briefly :

map.zoomToExtent(vectors.getDataExtent());

.

getDataExtent

getDataExtent: function ()

Calculates the max extent which includes all of the features.

.

zoomToExtent

zoomToExtent: function(   bounds,
  closest )

Zoom to the passed in bounds, recenter

i hope it helps you...