我不想在地图上有一个标记,这个位置是动态更新的。 当我在geolocation.on函数内创建图层时('更改' -event它可以工作,但每次地理位置更改时都会添加图层。因此我想在该函数之外创建图层并更新只有标记的位置。
使用下面的代码,我得到一个' TypeError:a为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);
});
答案 0 :(得分:0)
由ol.Geolocation
包装的浏览器Geolocation API是异步的。启动后,geolocation.getPosition()
将始终返回undefined
,直到第一次更改事件。
正确的做法是在更改事件处理程序中获取坐标后添加该功能。
您需要使用条件来确定是否应添加更新功能。
答案 1 :(得分:0)
我稍微更改了代码,因此我首先创建了一个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);
});