OpenLayers display all markers on screen

Got it working using zoomToExtent()

var newBound = OpenLayers.Bounds();

For each marker lonlat:

newBound.extend(lonLat);

Then pass it to the function:

map.zoomToExtent(newBound);

This is an old thread, but with changes to OpenLayers I thought I'd post a new solution to this. If you are using a ol.source.Vector as your layer source then you can call the following line to fit the map view around your data.

map.getView().fit(vectorSource.getExtent());

This simultaneously centers the map and sets the zoom so that all of your data is visible at once.


A similar way to do it, avoiding a loop, is given by OpenLayers getDataExtent() function here. You need to apply it on the layer containing your markers :

var newBound = map.myLayer.getDataExtent();
map.zoomToExtent(newBound);