【问题标题】:Google Maps API 3: Get Coordinates from Right-ClickGoogle Maps API 3:通过右键单击获取坐标
【发布时间】:2011-12-15 21:14:06
【问题描述】:

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

我有一个运行良好的 Google 地图实时预览,现在我想做的是在地图上添加一个右键单击事件,该事件会通过单击坐标填充纬度/经度文本框。

这可能吗?

我知道如何添加事件侦听器,并查看了 API 文档,但没有看到任何这样做的东西。我知道你可以在他们网站上的谷歌地图上做到这一点。

【问题讨论】:

  • 我想我找到了一些东西,fromDivPixelToLatLng 看起来不错。如果可行,我将尝试并重新发布解决方案

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


【解决方案1】:
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);
});

【讨论】:

  • 大声笑,我花了将近半天的时间写代码,刚刚回来查看,删除它,因为这正是它。谢谢!!!
  • 如何获取点击了哪个标记?通过将它们存储在一个数组中?
  • 相同的代码但将“右键单击”更改为“单击”使其适用于左键单击。您还可以在此处查看所有直播活动:developers.google.com/maps/documentation/javascript/events
【解决方案2】:

您可以创建一个 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>

【讨论】:

    猜你喜欢
    • 2014-01-05
    • 2012-09-23
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多