Search code examples
javascriptopenlayersopenstreetmap

OpenLayers display all markers on screen


How do I get all the markers on the map so the users can see all of them?

I have got some amount of markers. I am displaying them on the map. The center LonLat I get from taking the average of the highest and the lowest numbers of the lon and lat of all my markers.

So I set my map to the center point of all my markers using:

map.setCenter(centerLonLat, 8);

8 is just a random zooming level. Is there any way to calculate the perfect zooming level so all the markers are displayed in the map?


Solution

  • 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);