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
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
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
map: map
});
this.placeMarker(coordinates, this.map);
placeMarker(location, map) {
var marker = new google.maps.Marker({
position: location,
map: map
});
this.markersArray.push(marker);
}
@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);
}
}
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);
}
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
});
}
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);
}