0

I wan't to have a marker on the map, which position is dynamically updated. When I create the layer inside the function of the geolocation.on('change'-event it works, but the layer is added each time the geolocation changes. Therefore I wanted to create the layer outside that function and update only the position of the marker.

With the folowing code I get an 'TypeError: a is null'

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, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    opacity: 0.75,
    src: './_img/marker_.png'
  })
});

var pos1 = geolocation.getPosition();

var iconFeature = new ol.Feature({
   geometry: new ol.geom.Point(pos1)
});         
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);        
}); 

2 Answers 2

0

The browser Geolocation API, which is wrapped by ol.Geolocation, is asynchronous. After initiation, geolocation.getPosition() will always return undefined until the first change event.

The proper thing to do is to add the feature once you get a coordinate, in the change event handler.

You will need to use a conditional to determine if you should add ore update a feature.

0

I changed the code a bit, so that I created first an iconFeature, that wasn't already bound to a ol.geom.Point()-position. By this way there was no need to use geolocation.getPosition(). Later in the geolocation.on('change')-event I assigned the actual position to the geometry of the iconFeature.

Works like espected

// 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); 

// Update the position of the marker dynamically and zoom to position
  geolocation.on('change', function() {
    var pos = geolocation.getPosition();
    iconFeature.setGeometry(new ol.geom.Point(pos));
    view.setCenter(pos);
    view.setZoom(18); 
  });
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.