计算我的速度与地理定位API javascript

Calculate My Speed With Geolocation API javascript

本文关键字:定位 API javascript 我的 速度 计算      更新时间:2023-09-26

可以通过Google Maps javascript for android的地理定位来计算移动设备的移动速度?

至少如果你使用本地地理定位服务提供的geolocation插件,你得到的位置足够准确,从中你可以计算速度

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);

其中toRad函数来自Caspar Kleijne的答案,两个坐标之间的距离计算来自cletus的答案,t2t1为单位,纬度(lat1 &Lat2)和经度(lng1 &

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

同样的公式当然也适用于Google Maps的情况,但在这种情况下,我要检查计算的准确性,因为即使是网络延迟也可能导致一些测量误差,如果时间间隔太短,这些误差很容易成倍增加。