Reputation: 83
I have this code for displaying the current position of vehichles
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);
I need to update the position of the vehichles in the next ajax call. My addMarker function is as follows
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;
}
As this function returns the iconFeature, I can use setCoordinate function. But doing so wont update the position. Any idea how to do it??
Upvotes: 3
Views: 4848
Reputation: 3081
init your iconfetaures, vector source and layer globally
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);
create a function to populate the markers
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);
}
And your call code should look like
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);
I have not test it cause I didnt have the time to create a fiddle. If you really need a concrete solution you should make a fiddle to help us in order to help you.
Upvotes: 4