[GIS] Zooming to point boundary using OpenLayers

openlayers-2

I'm wondering what the best strategy to position a map that has two points, using OpenLayers is. At the moment, my approach is to calculate the mid-point of the two points, and to zoom the map to that mid-point using the following approach:

var centerPoint = new OpenLayers.LonLat(lon, lat);      
map.setCenter(centerPoint, zoomLevel); 

However, this is not ideal as I don't know what the zoomLevel should be, so sometimes although the map is centered, the points are not visible.

Is there a better approach to dynamically position the map?

Best Answer

the best way is that:

map.zoomToExtent(vectorLayer.getDataExtent());

var firstExtent = firstLayer.getDataExtent();
var secondExtent = secondLayer.getDataExtent();

var totalBounds = firstExtent.extend(secondExtent);

map.zoomToExtent(totalBounds);