Check if option exists already
I'm building the options for the gMap plugin dynamically and need to know how to check to see if one of the markers already exists.
This is how it is b开发者_如何转开发eing built in javascript:
success: function(data) {
var markers = { controls: true, scrollwheel: true, markers: [], zoom: 8 };
$.each(data["events"], function(id, event) {
// .. do other stuff with the data
if(showmap) {
// add location to maps list prevent multiples
//
// How do I check to see if it already exists?
//
// event[] is a JSON Object, BTW
//
//if((markers.indexOf(event['LocLatitude']) == -1) && (markers.indexOf(event['LocLongitude']) == -1)) {
marker1 = { latitude: event['LocLatitude'],
longitude:event['LocLongitude'],
html: '"'+event['LocName']+'<br />'+event['LocAddress']+'<br />'+event['LocCity']+', '+event['LocState']+'"',
icon:{image: "/images/gmap_pin_orange.png",
iconsize: [26, 46],
iconanchor: [12,46],
infowindowanchor: [12, 0]
}
};
markers.markers.push(marker1);
//} // if((markers.indexOf(event['LocLatitude']) == -1)
} // if(showmap)
} // $.each(data["events"]
}, // success:
The commented code above shows how I was doing it when I was building it as a string, that technique no longer works. I need to know how to check to see if the marker being added already exists in markers.markers before it is pushed.
Instead of pushing the markers to the table, could you assign them using numeric IDs or somehow create IDs based on context? See my answer to this question: How to select and manipulate google maps (V3 JS API) marker by ID?
Here, I'm iterating through the markers and checking the ones I want, the return false breaks me out of the $.each, return true continues.
marker_exists = false;
$.each( markers.markers, function(i, n){
if(markers.markers[i].latitude == event['LocLatitude'] && markers.markers[i].longitude == event['LocLongitude']) {
if(markers.latitude == "") {
markers.latitude = event['LocLatitude'];
markers.longitude = event['LocLongitude'];
}
marker_exists = true;
return false;
} else {
return true;
}
});
精彩评论