点击添加标记到谷歌地图

我正在努力寻找一个非常简单的例子,说明如何在用户点击地图时向 Google Map 添加标记。

120442 次浏览

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

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

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

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

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