Remove old marker add new one after call ajax method every x second with OpenLayers
Remove old marker add new one after call ajax method every x second with OpenLayers
I want to change marker position for every x seconds using ajax method but i am facing 1 issue for that is the new marker is adding on OpenLayers but old marker is not removing from OpenLayers. I want to remove old marker first and then add new marker in updated place.
function ShowCurrentTime() {
var obj = {};
obj.device_id = $.trim($("[id*=txtdevice_id]").val());
var marker;
var mapOptions;
$.ajax({
url: "TRACKING.aspx/GetData",
data: JSON.stringify(obj),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data.d != '') {
var lat = data.d[1];
var lng = data.d[2];
}
$.each(data, function(index, value) {
var zoom = 13;
var marker = new OpenLayers.Layer.Markers("Markers");
var lonLat = new OpenLayers.LonLat(lng, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.addLayer(marker);
map.removeLayer(marker);
marker.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter(lonLat, zoom);
});
}
});
}
1 Answer
1
you are initializing the marker again in ajax, remove first and then initialize it again
this should work
function ShowCurrentTime() {
var obj = {};
obj.device_id = $.trim($("[id*=txtdevice_id]").val());
var marker = null;
var mapOptions;
$.ajax({
url: "TRACKING.aspx/GetData",
data: JSON.stringify(obj),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data.d != '') {
var lat = data.d[1];
var lng = data.d[2];
}
$.each(data, function(index, value) {
var zoom = 13;
if (marker != null) map.removeLayer(marker);
marker = new OpenLayers.Layer.Markers("Markers");
var lonLat = new OpenLayers.LonLat(lng, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
map.addLayer(marker);
marker.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter(lonLat, zoom);
});
}
});
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I put this code in my application. but its not removing old marker, old and new both marker still show, i want to remove old and add new one on updated place.
– Ravi
1 hour ago