[GIS] zoomToExtent on Vector Layer

openlayers-2

Can someone explain if I am doing this correctly please?

I've added some vectors to my map, now wish to zoom and centre the map based on the extends of those vectors.

I'm using the following code:

var dataExtent = borders.getDataExtent();

which, when examined in FireBug does return the following values:

CLASS_NAME    "OpenLayers.Bounds"
bottom         4187116.4740651
centerLonLat   null
left           -20037508.34
right          20037508.34
top            16852219.924326

And then I'm executing the following:

map.zoomToExtent(bounds, true);

(if it helps to determine if I'm indeed returning the correct values from the getDataExtend() function, the region should be Russia)

Do I need to convert those figures from the getDataExtent() to a different format?

I've also tried the following, which again didn't do anything:

    var dataExtent = borders.getDataExtent();
    console.log(dataExtent);

    var tl = new OpenLayers.Geometry.Point(dataExtent.top, dataExtent.left);
    tl = tl.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

    var br = new OpenLayers.Geometry.Point(dataExtent.bottom, dataExtent.right);
    br = br.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

    var bounds = new OpenLayers.Bounds(tl.x, tl.y, br.x, br.y);
    map.zoomToExtent(bounds, true);

Best Answer

When you create the bounds variable by instantiating the class OpenLayers.Bounds, it seems to me that you are not using the constructor method properly. According to the OpenLayers API (http://goo.gl/Nq0Ry):

OpenLayers.Bounds Construct a new bounds object. Coordinates can either be passed as four arguments, or as a single argument.

Parameters (four arguments)

left {Number} The left bounds of the box. Note that for width calculations, this is assumed to be less than the right value.

bottom {Number} The bottom bounds of the box. Note that for height calculations, this is assumed to be more than the top value.

right {Number} The right bounds.

top {Number} The top bounds.