91

I'm struggling to find a very simple example of how to add a marker(s) to a Google Map when a user left clicks on the map.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Andre R.
  • 2,769
  • 2
  • 17
  • 17

6 Answers6

176

After much further research, i managed to find a solution.

google.maps.event.addListener(map, 'click', function(event) {
   placeMarker(event.latLng);
});

function placeMarker(location) {
    var marker = new google.maps.Marker({
        position: location, 
        map: map
    });
}
Stephan Celis
  • 2,492
  • 5
  • 23
  • 38
Andre R.
  • 2,769
  • 2
  • 17
  • 17
49

In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}
David Corral
  • 4,085
  • 3
  • 26
  • 34
22

This is actually a documented feature, and can be found here

// This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
  });

  function placeMarker(position, map) {
    var marker = new google.maps.Marker({
      position: position,
      map: map
    });  
    map.panTo(position);
  }
epson121
  • 443
  • 4
  • 7
19

To make the user able to add only once, and move the marker; You can set the marker on first click and then just change the position on subsequent clicks.

var marker;

google.maps.event.addListener(map, 'click', function(event) {
   placeMarker(event.latLng);
});


function placeMarker(location) {

    if (marker == null)
    {
          marker = new google.maps.Marker({
             position: location,
             map: map
          }); 
    } 
    else 
    {
        marker.setPosition(location); 
    } 
}
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Ahmed Samy
  • 302
  • 2
  • 12
6

Currently the method to add the listener to the map would be

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

And not

google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
});

Reference

Gmee
  • 61
  • 1
  • 5
-1

The best method to add marker 'on-click' is:

map.addListener('click', function(event) {  
    addMarker(event.latLng);  
  });