2013-04-09 26 views
8

如何获取地图上的所有标记,以便用户可以看到所有标记?OpenLayers在屏幕上显示所有标记

我有一些标记。我在地图上显示它们。 LonLat中心是从我所有标记的lon和lat的最高和最低数字的平均值中获得的。

map.setCenter(centerLonLat, 8); 

8只是随机缩放级别:

所以我用我的设置映射到我的所有标记的中心点。有什么办法可以计算出完美的缩放级别,所有的标记都显示在地图上?

回答

3

得到它的工作使用zoomToExtent()

var newBound = OpenLayers.Bounds(); 

对于每个标记lonlat:

newBound.extend(lonLat); 

然后将它传递给该函数:

map.zoomToExtent(newBound); 
+0

应该是:var newBound = new OpenLayers.Bounds(); – 2014-12-24 00:31:46

+0

我使用了你的解决方案,但不起作用,因为marker上的lonLat为null。但是我使用'getCoords()'并像这样工作:'bounds.extend(new OpenLayers.Geometry.Point(marker.getCoords()。lon,marker.getCoords()。lat).transform(fromProjection,toProjection)); ' – IgniteCoders 2015-06-25 18:19:07

+0

这是为ol2吗? ol3解决方案是什么? – Ries 2015-11-11 14:10:56

8

类似的方式做到这一点,从而避免一个循环,由OpenLayers getDataExtent() function here给出。您需要将其应用于包含标记的图层上:

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

你也可以使用它。但是因为我已经循环了我的标记,所以最好在该循环中进行。 – Klaasvaak 2013-04-10 10:02:24

1

这是一个旧线程,但对OpenLayers进行了更改,我想我会为此发布新的解决方案。如果您使用[ol.source.Vector][1]作为图层来源,则可以调用以下行来适应数据周围的地图视图。

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

这同时使地图居中并设置缩放比例,以便您的所有数据一次可见。