【问题标题】:Zoom (center) map to markers in OpenLayer3缩放(中心)地图到 OpenLayers 3 中的标记
【发布时间】:2016-05-23 06:19:48
【问题描述】:


我的 OpenLayer3 地图有问题。当我向地图添加一些标记时,我想调整地图大小并更改缩放比例,以便在屏幕上设置所有标记。

我的代码如下:

/** 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
  })
});

有没有办法将地图缩放到标记?

【问题讨论】:

    标签: javascript openlayers-3


    【解决方案1】:

    您的逻辑和某些 OL 参考中有一些错误。首先,您应该创建一个包含所有标记的 ol.Extent。然后使用地图的视图来适应它。

    // 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());
    

    这是一个笨蛋:

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

    【讨论】:

    • 好的,我会测试这个解决方案
    • 请@kagelos,检查你的答案,因为有时缩放会削减一些点。
    • 您的意思是在您手动放大之后或最初地图不包含所有点?
    • 是的,有时当我加载此脚本时,地图上不会显示一些标记。
    • @mdk 你能提供一个问题的例子吗?
    【解决方案2】:

    绘制矢量特征后,您可以使用以下方法获取范围:

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

    然后您可以使用以下命令放大到这个程度:

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

    所以如果你打算使用render 事件

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多