Reputation: 169
I have a set of markers on my map and am trying to update their position form an ajax call... The ajax call works fine and I can loop through the new values; however I cannot find a way to reference the markers (say by ID) so I can update their latLng.
Basically in the end I will need to.. 1.) Obtain a reference to a marker by a unique id 2.) Possibly loop through all markers
Thanks in advance - I am new and need a little help getting going - hopefully I can pass along the good will when I can :)
Code for ajax below - I the part about modifying the location of the marker is the part I don't know how to do - so in the code below I just add a new marker where I would really need to just update the position
var json = $.getJSON("json/tracking.php",function(data){
console.log("updated");
$.each(data,function(key,value){
//console.log(value.unit + " " + value.lat + " " + value.lng);
new google.maps.Marker({
map:map,
position: new google.maps.LatLng(value.lat,value.lng),
});
});
})
.success(function(){
//console.log("success");
})
.error(function(){
//console.log("error");
})
.complete(function(){
//console.log("complete");
});
},2000);
Upvotes: 2
Views: 3378
Reputation: 6779
Try this approach: I'm assuming your JSON is consistent in ordering the markers. newData
is pretending to be the new JSON data, when the map is clicked (outside a marker), the "new data" is fetched.
Here's the demo
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var data = [{unit:1, lat:0, lng:0},
{unit:2, lat:10, lng:0},
{unit:3, lat:20, lng:0}
];
var newData = [{unit:1, lat:0, lng:10},
{unit:2, lat:10, lng:20},
{unit:3, lat:20, lng:30}
];
var markers = {};
$.each(data,function(key,value){
//console.log(value.unit + " " + value.lat + " " + value.lng);
markers[key] = markers[key] || new google.maps.Marker({ map: map });
markers[key].setPosition(new google.maps.LatLng(value.lat,value.lng));
markers[key].setTitle(value.unit.toString());
});
google.maps.event.addListener(map, 'click', function() {
$.each(newData,function(key,value){
//console.log(value.unit + " " + value.lat + " " + value.lng);
markers[key] = markers[key] || new google.maps.Marker({ map: map });
markers[key].setPosition(new google.maps.LatLng(value.lat,value.lng));
markers[key].setTitle(value.unit.toString());
});
});
}
Upvotes: 0
Reputation: 2287
I'm inclined to store these in an array of objects as I create them, with any other information (e.g. id) stored as a property of the object. So create a markers array in the appropriate scope (probably outside of the scope of the json callback):
var markers = [];
var json = ...
markers.push({
id: //.. your unique id, or index
obj: new google.maps.Marker(...
});
Upvotes: 1