在 Openlayers 3 中更新地理位置标记的位置

update position of geolocation marker in Openlayers 3

我不想在地图上有一个标记,它的位置是动态更新的。 当我在 geolocation.on('change'-event 的函数内创建图层时它起作用,但每次地理位置更改时都会添加图层。因此我想在该函数外部创建图层并仅更新标记的位置。

通过以下代码,我得到了一个 '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);        
}); 

ol.Geolocation 包装的浏览器地理定位 API 是异步的。启动后,geolocation.getPosition() 将始终 return undefined 直到第一个更改事件。

正确的做法是在获得坐标后在更改事件处理程序中添加该功能。

您将需要使用条件来确定是否应该添加矿石更新功能。

我稍微更改了代码,因此我首先创建了一个 iconFeature,它尚未绑定到 ol.geom.Point() 位置。这样就不需要使用 geolocation.getPosition() 了。 后来在 geolocation.on('change') 事件中,我将实际位置分配给 iconFeature 的几何形状。

作品受人尊敬

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