gpt4 book ai didi

javascript - 动态更新标记 Openlayers 3 的位置

转载 作者:行者123 更新时间:2023-11-29 10:36:25 24 4
gpt4 key购买 nike

我有这段代码可以显示车辆的当前位置

var icon="http://www.openstreetmap.org/openlayers/img/marker.png";
window.setInterval (function () {
$.ajax({
url:"Dispatch_Action.vms?parameter=vehiclelive&action=customfilter",
type:"GET",
cache:false,
dataType: 'json',
success:function(response) {
$.each(response, function(recordCount, records) {
$.each(records, function(index, element) {

var createIcon=addMarker(element.LongitudePosition,element.LatitudePosition,icon);
});
});


}, error:function() {
console.log("Connection Failed");
}
});
}, 4000);

我需要在下一次 ajax 调用中更新车辆的位置。我的addMarker函数如下

function addMarker(lon,lat,icon) {


var iconFeatures=[];

var iconGeometry=new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326','EPSG:3857'));
var iconFeature = new ol.Feature({
geometry:iconGeometry
});

iconFeatures.push(iconFeature);

var vectorSource = new ol.source.Vector({
features: iconFeatures //add an array of features
});

var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.95,
src:icon
}))
});

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

map.addLayer(vectorLayer);
return iconFeature;

由于此函数返回 iconFeature,我可以使用 setCoordinate 函数。但这样做不会更新位置。知道怎么做吗??

最佳答案

全局初始化 iconfetaures、矢量源和图层

var iconFeatures=[];
var vectorSource = new ol.source.Vector({
features: iconFeatures //add an array of features
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});

map.addLayer(vectorLayer);

创建一个函数来填充标记

function addMarker(lon,lat,icon) {


var iconGeometry=new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326','EPSG:3857'));
var iconFeature = new ol.Feature({
geometry:iconGeometry
});

iconFeatures.push(iconFeature);
}

你的调用代码应该是这样的

var icon="http://www.openstreetmap.org/openlayers/img/marker.png";
window.setInterval (function () {
//clean the layer from any existing markers
vectorSource.clear();
$.ajax({
url:"Dispatch_Action.vms?parameter=vehiclelive&action=customfilter",
type:"GET",
cache:false,
dataType: 'json',
success:function(response) {
$.each(response, function(recordCount, records) {
$.each(records, function(index, element) {

var createIcon=addMarker(element.LongitudePosition,element.LatitudePosition,icon);
});
});
//and here add the newly created features to the layer
vectorSource.addFeatures(iconFeatures);

}, error:function() {
console.log("Connection Failed");
}
});
}, 4000);

我没有测试它,因为我没有时间创建 fiddle 。如果你真的需要一个具体的解决方案,你应该制作一个 fiddle 来帮助我们以帮助你。

关于javascript - 动态更新标记 Openlayers 3 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35696175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com