[GIS] Openlayers 2 – zoom to multiple coordinates

openlayers-2

I have multiple asset icons on a map

I want to be able to zoom to show all icons on the map
I have the Lat and Long of each asset

Currently, i have it working with 1 asset as I can use this code to zoom to the asset
map.setCenter(new OpenLayers.LonLat(obj.d[k].vLongitude, obj.d[k].vLatitude).transform(WGS84, map.getProjectionObject()), map.getZoom());

Do I need to pass in an array of co-ordinates?

Best Answer

create coordinate list

var obj={};
obj.d=[];
obj.d[0] ={};
obj.d[0].vLongitude = 45; 
obj.d[0].vLatitude= 45; 
obj.d[1] ={};
obj.d[1].vLongitude = 55; 
obj.d[1].vLatitude= 55;

create a markers layer

var markers = new OpenLayers.Layer.Markers( "Markers" );
            map.addLayer(markers);

and add all markers on map

for(var i=0;i<obj.d.length;i++){ 
 var size = new OpenLayers.Size(25,25);
            var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
            var icon = new OpenLayers.Icon('http://www.openlayers.org/api/img/zoom-world-mini.png',size,offset);
            markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(obj.d[i].vLongitude,obj.d[i].vLatitude),icon));
}

and

zoom to data extent

map.zoomToExtent(markers.getDataExtent());