Javascript/jquery Google marker refresh
I have a google map in which I render markers from a database via ajax. It works well except the markers redraw (old ones delete and new ones get drawn). The data I get back from ajax is开发者_JS百科 text form of comma separated variables. I am trying to figure an efficient way of deleting the data that is no longer applicable and adding the new ones. I think the best way to handle this as soon as I get the data back from the ajax post since that is when it is in purest form meaning before it gets turned into markers.
Has anyone done this before or have experience with is? If I were doing it in LINQ I would do some sort of except between the two lists of data. I don't know how to QUICKLY do it in js since the js is a slower part of the cycle.
There may not be enough detail in the question, but assuming the following:
- Ajax returns text that has a comma-separated list of unique marker ID's.
- You have a list, or an array from the previous ajax call of unique marker ID's.
- You want a list of markers to delete, and another list of markers to add.
If that's not true, then please clarify the question, adding details. "Before" and "After" would be good.
Otherwise, an approach like this should work:
Sample Data:
var oldMarkers = [ "Joe's Diner",
"Frank's Bail bonds",
"Precinct 9",
"Fence and Go"
];
var newMarkerStr = "Precinct 9, Memorial Hospital,"
+ " Frank's Bail bonds, Mary's shyster";
//-- Split on commas; strip out boundary whitespace.
var newMarkers = newMarkerStr.split (/(?:\s*,\s*)+(?!(?:\s*,\s*))/);
Process like so:
var toAdd = newMarkers.slice (); //-- Copy the array.
var toDelete = $.grep (oldMarkers, function (marker) {
var K = $.inArray (marker, newMarkers);
if (K == -1) {
//-- Old item not in the list, delete it.
return true;
}
else {
/*-- Old item is in the new list, mark it as
to be removed from the "add" list.
*/
toAdd[K] = -666;
}
return false;
} );
toAdd = $.map (toAdd, function (marker) {
return (marker == -666) ? null : marker;
} );
See it live at jsFiddle.
精彩评论