向用户显示坐标并触发事件

Show users coordinates and trigger event

本文关键字:事件 坐标 用户 显示      更新时间:2023-09-26

我正在使用谷歌地图实用程序库V3中的地理位置标记脚本来显示用户的位置。

我想要实现的(我是谷歌地图API的新手!)是:

  • 显示用户的当前坐标(例如,在页面上某处的简单CSS容器中)

  • 将事件连接到标记。当用户关闭时,我应该被触发。

感谢您的帮助!

要向用户显示坐标,您需要对 DOM 元素的引用。然后是更新内容的简单问题。

页面上的网页

<div id="UserCoordinates">Waiting on GPS Position ...</div>

在脚本中

google.maps.event.addListener(GeoMarker, 'position_changed', function() {
  var UserPosition = this.getPosition();
  var DisplayElement = document.getElementById('UserCoordinates');
  if(UserPosition === null) {
    DisplayElement.innerHTML = 'Waiting on GPS Position...';
  } else {
    DisplayElement.innerHTML =
        'Current Position: ' + UserPosition.toUrlValue();
  }
});

这将在用户更改时向用户显示其当前位置。如果要继续使用全屏地图,则可能需要将UserCoordinatesdiv 实现为地图控件。API 参考对此有一个很好的概述和多个示例。

当用户距离某个位置 X 米以内时显示信息窗口

这有点棘手,因为有多种场景需要处理,并且您不希望信息窗口在您的半径内移动时反复打开。

距离计算

我看到您的代码中有一个距离函数,但我建议使用 API 的球形几何库中的函数。您只需要使用 api 脚本标签专门加载库:

<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true_or_false">
</script>

然后,您需要添加到position_changed事件处理程序:

var IsWithinRadius = false; //assume they start outside of the circle
var RadiusInMeters = 1000; //within 1 km
var LocationOfInterest = map.getCenter();
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
  var UserPosition = this.getPosition();
  var DisplayElement = document.getElementById('UserCoordinates');
  if(UserPosition === null) {
    DisplayElement.innerHTML = 'Waiting on GPS Position...';
    IsWithinRadius = false; //you don't know where they are
  } else {
    DisplayElement.innerHTML =
        'Current Position: ' + UserPosition.toUrlValue();
    var IsCurrentPositionInRadius =
        Math.abs(google.maps.geometry.spherical.computeDistanceBetween(
            UserPosition, LocationOfInterest)) <= RadiusInMeters;
    var JustEnteredRadius = !IsWithinRadius && IsCurrentPositionInRadius;
    IsWithinRadius = IsCurrentPositionInRadius;
    if(JustEnteredRadius) {
      //trigger action here.
      alert("Within raidus");
    }
  }
});