Reputation: 29
It is possible to calculate the speed of the mobile device moving through the geolocation of Google Maps javascript for android ?
Upvotes: 2
Views: 7805
Reputation: 7405
At least if you use the native geolocation service provided by Geolocation plugin you get the location accurate enough from which you can calculate the speed as
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);
where the toRad function for the Number is from Caspar Kleijne's answer, the calculation for distance between the two coordinates is from cletus' answer, the t2 and t1 are in seconds and the latitudes (lat1 & lat2) and longitudes (lng1 & lng2) are floats.
The main idea in code is the following: 1. Get initial location and store time when in that location, 2. Fetch another location, and when gotten, use the locations and times to call the calculateSpeed function.
The same formula of course applies to the Google Maps case, but in that case I'd review the exactness of calculation since even the network lag might cause some measurement errors that multiply easily if the time interval is too short.
Upvotes: 3