简体   繁体   中英

Zoom (center) map to markers in OpenLayer3


I have problem with my OpenLayer3 map. 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. First you should create an ol.Extent that contains all the markers. 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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