14

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?

Klaasvaak
  • 5,634
  • 15
  • 45
  • 68

3 Answers3

11

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);
AnthonyLeGovic
  • 2,335
  • 1
  • 13
  • 22
  • 1
    You could use that as well. But since I am already looping over my markers it would be better to do it in that loop. – Klaasvaak Apr 10 '13 at 10:02
10

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.

iGroza
  • 645
  • 7
  • 9
UnboxedSoul
  • 101
  • 1
  • 3
5

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);
Klaasvaak
  • 5,634
  • 15
  • 45
  • 68
  • should be: var newBound = new OpenLayers.Bounds(); – Hayden Thring Dec 24 '14 at 00:31
  • i used your solution, but does not work because lonLat on marker is null. But i used `getCoords()` and work like this: `bounds.extend(new OpenLayers.Geometry.Point(marker.getCoords().lon, marker.getCoords().lat).transform(fromProjection, toProjection));` – IgniteCoders Jun 25 '15 at 18:19
  • Is this for ol2? What would the ol3 solution be? – Ries Nov 11 '15 at 14:10