Calculate My Speed With Geolocation API javascript
是否可以通过Android的Google Maps javascript地理位置计算移动设备的移动速度?
至少如果您使用Geolocation插件提供的本地地理定位服务,您将获得足够准确的位置,据此可以将速度计算为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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); |
其中Number的toRad函数来自Caspar Kleijne的答案,两个坐标之间距离的计算来自cletus的答案,t2和t1以秒为单位,纬度为(lat1