Reputation: 6436
I have the following function to add one single marker but I want to add multiple markers by clicking on the map. I have Googled but I can't get any straight answer on how I can solve this problem.
function placeMarker(location) {
if(marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: gm_map,
draggable: true
});
}
}
I know I need to use Array()
but I don't know exactly how. How can I solve my problem?
DEMO: removed because the problem has been solved.
Upvotes: 1
Views: 2988
Reputation: 4473
Do you need to use the marker
variable outside of the placeMarker
function? Your function is not deleting the marker, it is checking to see if the marker variable exists and moves the marker using the setPosition
function. You need to remove that line if you want multiple markers to exist.
function placeMarker(location) {
//marker variable will only exist inside this function
var marker = new google.maps.Marker({
position: location,
map: gm_map,
draggable: true
});
}
Here is an example: http://jsfiddle.net/bryan_weaver/aEyfW/
Upvotes: 2
Reputation: 31912
Ok, you need to have an event listener for the 'click' event on the map. And this needs to pass the currently-clicked location to your placeMarker function. Try this (add this event listener in the same place where you initialise your map)
google.maps.event.addListener(gm_map, 'click', function(event) {
placeMarker(event.latLng);
});
And modify your placeMarker function, so instead of having one global variable marker which you update with each click, create a new marker each time:
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: gm_map,
draggable: true
});
}
Upvotes: 1