[GIS] Dynamically update position of geolocation marker in Openlayers 3

geolocationopenlayers

I've followed the instructions of the following post: l3 (OpenLayers-3) add geolocation marker to add a geolocation marker to an ol3 map. The probem is, that the mentioned post ends up with proposing tho use the geolocation.once ('change:position')-event to avoid multiple recreation of the geolocation-marker-layer. This approach is contradictory to the intention of having an marker that updates its position in real time.

I've tried to define the iconlayer outside the geolocation.on('change')-event supposing, that it would be possible to just update the coordinates every time the event is fired.

I now get an TypeError: a is null and I cannot see where the problem lies.

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

  var iconStyle = new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 100],
      anchorXUnits: 'fraction',
      anchorYUnits: 'pixels',
      opacity: 1.0,
      src: './_img/marker_.png'
       })
      });

  var pos_first = geolocation.getPosition();

  var iconFeature = new ol.Feature({
      geometry: new ol.geom.Point(pos_first)
  });   

  var iconSource = new ol.source.Vector({
    features: [iconFeature]
  });

  var iconLayer = new ol.layer.Vector({
    source: iconSource,
    style : iconStyle
  });

  map.addLayer(iconLayer); 

  geolocation.on('change', function() {
    var pos_upd = geolocation.getPosition();
    iconFeature.getGeometry().setCoordinates(pos_upd);
    view.setCenter(pos_upd);
    view.setZoom(18); 
  });

Best Answer

After trying a lot I found the following solution to add only one iconFeature and update the position in the geolocation.on('change') event.

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

  var iconStyle = new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 100],
      anchorXUnits: 'fraction',
      anchorYUnits: 'pixels',
      opacity: 1.0,
      src: './_img/marker_.png'
       })
      });

// add an empty iconFeature to the source of the layer
  var iconFeature = new ol.Feature();   
  var iconSource = new ol.source.Vector({
    features: [iconFeature]
  });    
  var iconLayer = new ol.layer.Vector({
    source: iconSource,
    style : iconStyle
  });    
  map.addLayer(iconLayer); 

  geolocation.on('change', function() {
    var pos = geolocation.getPosition();
    iconFeature.setGeometry(new ol.geom.Point(pos));
    view.setCenter(pos);
    view.setZoom(18); 
  });

This works now fine.

Related Question