Reputation: 7768
I am trying to solve a conundrum using google maps and js. I never worked with google maps and my knowledge of JS is limited.
My MAIN question is: How do I Create multiple independent markers on google map, store them into some sort of data structure and then delete particular markers when I need it?
For example, each marker has it's own id number, I get its lat and lon and them I use this function to add it to map:
function createMarkers(geocoder, map, name, latitude, longitude, ib, image) {
//Setting the onclick marker function
var onMarkerClick = function() {
var marker = this;
var latLng = marker.getPosition();
ib.setContent(name);
ib.open(map, marker);
};
google.maps.event.addListener(map, 'click', function() {
ib.close();
});
//In array lat long is saved as an string, so need to convert it into int.
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: new google.maps.LatLng(lat, lng),
title: name
});
//Adding the marker.
google.maps.event.addListener(marker, 'click', onMarkerClick);
}
Upvotes: 1
Views: 2925
Reputation: 522
According to Google Maps API V3, marker instance has the method setMap. it "Renders the marker on the specified map or panorama. If map is set to null, the marker will be removed." extrated from Google Maps API V3 Documentation
something like this
marker.setMap(null);
by other side, if you want to remove an specific marker, as well you said, u will have to hold marker instances in some data strucutre, in order to be able to get access to specific markers. As you have an id, considering that marker's id is unique, you can use a hash. Something like that.
// this variable must be global and accesible from your createMarkers method
var all_markers = {};
function createMarkers(geocoder, map, name, latitude, longitude, id, image) {
//........
var marker = new google.maps.Marker({
map: map,
icon: image,
position: new google.maps.LatLng(lat, lng),
title: name
});
all_markers[id] = marker;
//.....................
}
function removeMarker(id) {
all_markers[id].setMap(null);
delete all_markers[id];
}
Upvotes: 2