简体   繁体   English

单击时将标记添加到 Google 地图

[英]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.当用户左键单击地图时,我很难找到一个非常简单的示例,说明如何向 Google 地图添加标记。

I have looked around for the past couple of hours, and consulted the Google Maps API documentation, and would appreciate some help!过去几个小时我环顾四周,并查阅了 Google Maps API 文档,希望得到一些帮助!

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

In 2017, the solution is: 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);
}

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

@Chaibi Alaa, To make the user able to add only once, and move the marker; @Chaibi Alaa,使用户只能添加一次,并移动标记; 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); 
    } 
}

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 参考

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM