Search code examples
openlayers-6

Centering and zooming out view with multiple markers


Have created a map on which have added multiple markers:

 function add_map_point(lat, lon) {
      let vectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector({
          features: [new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lat), parseFloat(lon)], 'EPSG:4326', 'EPSG:3857')),
          })]
        }),
        style: new ol.style.Style({
          image: new ol.style.Icon({
            anchor: [0.5, 0.5],
            anchorXUnits: "fraction",
            anchorYUnits: "fraction",
            src: fsi.constants.image_location + "/Maps/marker-red.png"
          })
        })
      });

      map.addLayer(vectorLayer);
    }

    // instantiates map 
    const map = new ol.Map({
      target: identifier,
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      view: new ol.View({
        center: ol.proj.fromLonLat([getCurrentPosition().lon, getCurrentPosition().lat]),
        zoom: opts.zoom
      })
    })

and am adding markers to the map:

if (pinpoints.length > 0) {
  // shows pinpoints on the map
  pinpoints.map(el => {
    return add_map_point(el.lon, el.lat);
  })
}
else {
  var latLon = getCurrentPosition();

  view: new ol.View({
    center: ol.proj.fromLonLat([latLon.lon, latLon.lon]),
    zoom: opts.zoom
  })
}

After adding the markers I would like the map to zoom as much as possible so that all markers are visible at once. How to do that?


Solution

  • With your current code you would need to build an array of the transformed coordinates and fit to their bounding extent

    map.getView().fit(ol.extent.boundingExtent(arrayOfCoordinates));
    

    Do you really need a separate layer for each marker? If you created a single layer and your added all the markers to that you could use

    map.getView().fit(vectorLayer.getSource().getExtent());