简体   繁体   English

缩放(中心)地图到OpenLayer3中的标记

[英]Zoom (center) map to markers in OpenLayer3


I have problem with my OpenLayer3 map. 我的OpenLayer3地图有问题。 When I add some markers to map I want to resize my map and change the zoom so that all markers were set on the screen. 当我在地图上添加一些标记时,我想调整地图大小并更改缩放比例,以便在屏幕上设置所有标记。

My code looks like: 我的代码如下:

/** CREATE MARKERS **/
for (var i=0;i<1;i++){
  var iconFeature = new ol.Feature({
    geometry: new
      ol.geom.Point(ol.proj.transform([Math.random()*360-180, Math.random()*180-90], 'EPSG:4326',   'EPSG:3857'))
  });
  vectorSource.addFeature(iconFeature);
  var newBound = ol.Bounds();
  newBound.extend([Math.random()*360-180, Math.random()*180-90]);
  map.zoomToExtent(newBound);
}

/** MARKER STYLE **/
var iconStyle = [
  new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 1,
    scale: 0.07,
    src: 'marker.png'
  }))
  })
];

/** ADD LAYER VECTOR **/
var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: iconStyle
});


/** INIT MAP **/
var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'sat'})
    }),
    vectorLayer
  ],
  overlays: [overlay],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

Is there a way to zoom the map to markers? 有没有办法将地图缩放到标记?

You have some errors in your logic and in some OL references. 您的逻辑和某些OL参考中都有一些错误。 First you should create an ol.Extent that contains all the markers. 首先,您应该创建一个包含所有标记的ol.Extent。 Then use the map's view to fit it in. 然后使用地图的视图进行调整。

// create ten random markers
for (var i = 0; i < 10; i++) {
    var point = new ol.geom.Point(ol.proj.transform([Math.random() * 50, Math.random() * 50], 'EPSG:4326', 'EPSG:3857'));
    var iconFeature = new ol.Feature({
        geometry: point
    });

    vectorSource.addFeature(iconFeature);
}


// make the map's view to zoom and pan enough to display all the points
map.getView().fit(vectorSource.getExtent(), map.getSize());

Here's a plunker: 这是一个矮人:

https://plnkr.co/edit/KVL14vdOSqJBxZz44s3u?p=preview https://plnkr.co/edit/KVL14vdOSqJBxZz44s3u?p=preview

Once your vector features has been drawn you may get the extent using: 绘制矢量特征后,您可以使用以下方法获得范围:

vector.on('render',function(e){
var myextent = vector.getSource().getExtent();
})

And then you may zoom to this extent using: 然后,您可以使用以下方法缩放到此程度:

map.getView().fit(myextent , map.getSize());

So if you are going to use the render event 因此,如果您要使用render事件

vector.on('render',function(e){
map.getView().fit(vector.getSource().getExtent(), map.getSize());
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM