Search code examples
javascriptopenlayersdom-eventsopenlayers-3

How to zoom in on current position on load of page


I am new in open-layer I am trying to zoom in on current location on load on page I don't want to use any button, I was trying to get the output when I load a page it will redirect to my current location with zoom level 12. I tried to change the view by calling function but it is not working for me.

I tried below on load on page but it is not working:

  el('track').addEventListener('load', function() {
    geolocation.setTracking(this.load);
  });

Solution

  • You need to do two things.

    Firstly, add tracking: true to the following.

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

    then add this line map.getView().setCenter(geolocation.getPosition()); to the following function.

      geolocation.on('change:position', function() {
        map.getView().setCenter(geolocation.getPosition());
        var coordinates = geolocation.getPosition();
        positionFeature.setGeometry(coordinates ?
          new ol.geom.Point(coordinates) : null);
      });
    

    See updated plunker here.