【问题标题】:Google Maps API (JS): check if I reached my destinationGoogle Maps API (JS):检查我是否到达目的地
【发布时间】:2014-11-27 20:28:53
【问题描述】:

我正在为使用 Google Maps API 的 iPad 开发 HTML5 网络应用程序。这个 API 对我来说是新的,我已经搜索了许多与之相关的问题的答案。标记、信息窗口、路线、地理位置、街景。关于这一切的最有用的信息可以在官方文档中找到:

https://developers.google.com/maps/documentation/javascript/3.exp/reference?hl=ru

但是,我仍然找不到解决一个(也许是简单的)问题的方法。例如,我创建了一个新的地图实例和一个标记(目的地),开始观察我的位置(GEO 位置)并绘制了一条通往该标记位置的路线。 我如何检查何时到达目的地?我已经寻找了 DirectionsService、DirectionsRenderer 等的适当事件,但没有结果。另外,我在这个网站上找到了相同的主题,但它是关于 Android 开发的,而不是 JS (Android: How to check that whether i reach/near my Destination?)。

无奈之下,我发明了自己的解决方案,但似乎无法正常工作(我还没有完全测试过,我会在接下来的几天内完成)。我想如果我将我当前位置的 lat&lng 与目的地的 lat&lng 进行比较 - 那么我可以捕捉到到达目的地的时刻:

if (myPosition.lat() == dest.marker.position.lat() && myPosition.lng() == dest.marker.position.lng()) {
     alert('You have arrived!');
}

这段代码在navigator.geolocation.watchPosition成功的watch位置回调中执行

你有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    LatLng 是高精度的值,你不能指望两个标记的位置会完全匹配。

    添加容差:

    //tolerance 50 meters
    //requires the geometry-library 
    if(google.maps.geometry.spherical
       .computeDistanceBetween(myPosition,dest.marker.position)<50){
      alert('You have arrived!');
    } 
    

    【讨论】:

    • 可能应该使用marker.getPosition()而不是无证的.position
    【解决方案2】:

    我认为自制解决方案不是一个好主意,因为地图 API 可以完成所有操作。

    Using Google Maps API to get travel time data

    【讨论】:

      【解决方案3】:

      对于 Android Studio 用户:

      获取currentLocation和destinationLocation的对象

      Location currentLocation;      // use fusedLocationProviderService
      Location destinationLocation = new Location("");  // set Lat and Long 
      destinationLocation.setLatitude(122.1234123); // like this
      
       if (location.distanceTo(new Location("")) < 30) { // meters
                          Toast.makeText(MainActivity.this, "Toast you have reached",
                                  Toast.LENGTH_SHORT).show();
                      }
      
      

      【讨论】:

        猜你喜欢
        • 2018-08-26
        • 2014-01-25
        • 1970-01-01
        • 2016-09-02
        • 2012-03-02
        • 2017-01-14
        • 2013-03-29
        • 2017-10-10
        • 1970-01-01
        相关资源
        最近更新 更多