Google Maps API 3:从右键单击获取坐标

时间:2011-10-26 16:25:52

标签: google-maps google-maps-api-3

当用户向数据库输入新记录时,我有2个lat和lon文本框。

我有一个很棒的Google地图实时预览,现在我要做的是在地图上添加一个右键单击事件,在点击coord的情况下填充lat / lon文本框。

这甚至可能吗?

我知道如何添加事件监听器,并浏览了API文档,但没有看到任何这样做。我知道你可以在google网站上的地图上做到这一点。

2 个答案:

答案 0 :(得分:154)

google.maps.event.addListener(map, "rightclick", function(event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    // populate yor box/field with lat, lng
    alert("Lat=" + lat + "; Lng=" + lng);
});

答案 1 :(得分:3)

您可以创建一个InfoWindow对象(class documentation here)并附加一个rightclick事件处理程序,该处理程序将使用地图上单击位置的纬度和经度填充它。

function initMap() {
  var myOptions = {
      zoom: 6,
      center: new google.maps.LatLng(-33.8688, 151.2093)
    },
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
    marker = new google.maps.Marker({
      map: map,
    }),
    infowindow = new google.maps.InfoWindow;
  map.addListener('rightclick', function(e) {
    map.setCenter(e.latLng);
    marker.setPosition(e.latLng);
    infowindow.setContent("Latitude: " + e.latLng.lat() +
      "<br>" + "Longitude: " + e.latLng.lng());
    infowindow.open(map, marker);
  });
}
html,
body {
  height: 100%;
}
#map-canvas {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIPPUQ0PSWMjTsgvIWRRcJv3LGfRzGmnA&callback=initMap" async defer></script>
<div id="map-canvas"></div>