[google-maps] Add marker to Google Map on Click

I'm surprisingly 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.

I have looked around for the past couple of hours, and consulted the Google Maps API documentation, and would appreciate some help!

This question is related to google-maps google-maps-api-3

The answer is


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);
}

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


@Chaibi Alaa, 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); 
    } 
}

  1. First declare the marker:
this.marker = new google.maps.Marker({
   position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
   map: map
});
  1. Call the method to plot the marker on click:
this.placeMarker(coordinates, this.map);
  1. Define the function:
placeMarker(location, map) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    this.markersArray.push(marker);
}

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);
  }