当前位置: 代码迷 >> JavaScript >> 使用地理位置API计算我的速度
  详细解决方案

使用地理位置API计算我的速度

热度:53   发布时间:2023-06-08 09:37:31.0

是否可以通过Android的Google Maps javascript的地理位置来计算移动设备的移动速度?

至少如果您使用提供的本地地理定位服务,您将获得足够准确的位置,据此可以计算速度为

function calculateSpeed(t1, lat1, lng1, t2, lat2, lng2) {
  // From Caspar Kleijne's answer starts
  /** Converts numeric degrees to radians */
  if (typeof(Number.prototype.toRad) === "undefined") {
    Number.prototype.toRad = function() {
      return this * Math.PI / 180;
    }
  }
  // From Caspar Kleijne's answer ends
  // From cletus' answer starts
  var R = 6371; // km
  var dLat = (lat2-lat1).toRad();
  var dLon = (lon2-lon1).toRad();
  var lat1 = lat1.toRad();
  var lat2 = lat2.toRad();

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) *    Math.cos(lat2); 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var distance = R * c;
  // From cletus' answer ends

  return distance / t2 - t1;
}

function firstGeolocationSuccess(position1) {
  var t1 = Date.now();
  navigator.geolocation.getCurrentPosition(
    function (position2) {
      var speed = calculateSpeed(t1 / 1000, position1.coords.latitude, position1.coords.longitude, Date.now() / 1000, position2.coords.latitude, position2.coords.longitude);
    }
}
navigator.geolocation.getCurrentPosition(firstGeolocationSuccess);

其中NumbertoRad函数来自 ,两个坐标之间的距离的计算来自 , t2t1秒为单位 ,纬度(lat1&lat2)和经度(lng1&lng2)为彩车。

代码中的主要思想如下:1.获取初始位置并在该位置存储时间,2.获取另一个位置,获取后,使用位置和时间调用calculateSpeed函数。

当然,相同的公式适用于Google Maps情况,但是在这种情况下,我将回顾计算的准确性,因为即使网络滞后也可能会导致一些测量误差,如果时间间隔太短,它们很容易相乘。