Keezartn
Keezartn

Reputation: 1

Openlayers - Add control: zoom/pan to current location

I'm trying to add an ol.control button to the map that zooms/pans to my current location. I've extracted my location coordinates with:

var geolocation = new ol.Geolocation({
        projection: map.getView().getProjection(),
        tracking: true
    });
geolocation.getPosition(); //this shows the coordinates (e.g.[591374.2306195896, 6746799.171545821])

Now I want to use these as input for a "zoom to" ol.control button. As one would use ol.control.ZoomToExtent, which creates a control button. e.g.:

map.addControl(zoomToExtentControl);

zoomToExtentControl = new ol.control.ZoomToExtent({
  extent: [-1013450.0281739295, 3594671.9021477713, 6578887.117336057, 10110775.689402476],
  className: 'custom-zoom-extent',
  label: '🔍'
});

Please help me out :-)

Upvotes: 0

Views: 1166

Answers (1)

Mike
Mike

Reputation: 17962

The extent array used for the ZoomToExtent can be dynamically updated with the accuracy extent from the geolocation

var geolocation = new ol.Geolocation({
        projection: map.getView().getProjection(),
        tracking: true
    });

var extent = ol.extent.createEmpty();

geolocation.on('change:accuracyGeometry', function() {
    geolocation.getAccuracyGeometry().getExtent(extent);
});

zoomToExtentControl = new ol.control.ZoomToExtent({
  extent: extent,
  className: 'custom-zoom-extent',
  label: '🔍'
});

Upvotes: 1

Related Questions