点击添加标记到Google Map


87

我很难找到一个非常简单的示例,说明当用户在地图上单击鼠标左键时如何在Google地图上添加标记。

在过去的几个小时中,我环顾了四周,并查阅了Google Maps API文档,希望对您有所帮助!

Answers:


169

经过更多的研究,我设法找到了解决方案。

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

function placeMarker(location) {
    var marker = new google.maps.Marker({
        position: location, 
        map: map
    });
}

7
我们可以使用户只能添加一次吗?并移动标记?
Chaibi Alaa

请给示例链接
Sopo

43

在2017年,解决方案是:

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

20

这实际上是一个已记录的功能,可以在这里找到

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

14

@Chaibi Alaa,使用户只能添加一次并移动标记;您可以在第一次单击时设置标记,然后在以后的单击中更改位置。

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

6

目前,将侦听器添加到地图的方法是

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

并不是

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

参考


0
  1. 首先声明标记:
this.marker = new google.maps.Marker({
   position: new google.maps.LatLng(12.924640523603115,77.61965398949724),
   map: map
});
  1. 调用该方法以在单击时绘制标记:
this.placeMarker(coordinates, this.map);
  1. 定义功能:
placeMarker(location, map) {
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    this.markersArray.push(marker);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.