Javascript Calculate the total distance by a loop - javascript

I got the script that calculates the distance and I spent my coordinates with 2 points ( pos1 , pos2 ) ( both are geolocated ) Then I put a loop that recharges the script every 5/10 seconds and I saved the distance with a LocalStorage out a loop .
Now I want out of the loop there is a variable that calculates the total distance , or rather that calculates all distances that are passed by the loop.
This is the code:
(function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos1 = position.coords.latitude;
pos11= position.coords.longitude;
console.log('latitudine ' + pos1);
console.log('longitudine ' + pos11);
//Passano 2 secondi
setTimeout(function(){
pos2 = 45.2968571;
pos22 = 12.034978499999966;
console.log('latitudine ' + pos2);
console.log('longitudine ' + pos22);
alert("Sono passati 2 secondi");
},2000);
// Converte in radianti
setTimeout(function(){
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 = (pos2-pos1).toRad();
var dLon = (pos22-pos11).toRad();
var lat1 = pos1.toRad();
var lat2 = pos2.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 distance1 = R * c;
var distance2 = distance1;
console.log(distance1, distance2);
alert('hai percorso: ' + distance1 + 'm ');
var distance2 = localStorage.setItem('key', distance2);
},2000);
})
}
setTimeout(arguments.callee, 10000);
})();
(function(){
setTimeout(function(){
var distanza = localStorage.getItem('key', 'distance2');
var distanza1 = distanza;
// here i wont calculate the total distance
console.log('prima: ' + distanza + 'n\totale: ' + total);
},6000);
setTimeout(arguments.callee,10000);
})();

Related

Limiting the great circle

I need to limit the radius of the great circle problem. The circle will extend until it hits another item.
I need it to limit the range of the circle to 5 miles
Here is my code
function find_closest_ticket(ticket, lat, lng) {
// var lat = map.position.coords.latitude;
// var lon = map.position.coords.longitude;
// lat = 24.709254;
// lng = -81.381927;
var R = 6371; // radius of earth in km
var distances = [];
var closest = -1;
for (i = 0; i < ticket.length; i++) {
var mlat = ticket[i].soLAT;
var mlng = ticket[i].soLNG;
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
return closest;
}
First, it is surprising you use a function that returns a radius in km, and then want to limit it to 5 miles. You should make up your mind: either write the function to return miles and add the limit in miles, or leave the function as-is and limit it by km (8 km is roughly 5 miles).
If you want to use miles, then change this line:
var R = 6371; // radius of earth in km
to:
var R = 3959; // radius of earth in miles
and replace:
return closest;
by:
return Math.min(5, closest);
Alternatively, if you want to stick to km, then only replace:
return closest;
by:
return Math.min(8, closest);

Geolocation does not work on smartphone

I want to implement geolocation in my app.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition, errorGettingPosition);
}
function getPosition(position) {
var myLatitude = position.coords.latitude;
var myLongitude = position.coords.longitude;
var radiusEarth = 6371;
myLongitude = myLongitude * (Math.PI / 180);
myLatitude = myLatitude * (Math.PI / 180);
var x0 = myLongitude * radiusEarth * Math.cos(myLatitude);
var y0 = myLatitude * radiusEarth;
for (var i = 0; i < list.length; i++) {
var vendorLongitude = list[i].Longitude = list[i].Longitude * (Math.PI / 180);
var vendorLatitude = list[i].Latitude = list[i].Latitude * (Math.PI / 180);
var x1 = vendorLongitude * radiusEarth * Math.cos(vendorLatitude);
var y1 = vendorLatitude * radiusEarth;
var dx = x0 - x1;
var dy = y0 - y1;
var d = Math.sqrt((dx * dx) + (dy * dy));
if (d < 1) {
list[i].Distance = Math.round(d * 1000) + " m";
} else {
list[i].Distance = Math.round(d * 10) / 10 + " km";
}
}
//add vendors to scope
$scope.vendors = list;
}
function errorGettingPosition(err) {
if (err.code == 1) {
alert("User denied geolocation.");
}
else if (err.code == 2) {
alert("Position unavailable.");
}
else if (err.code == 3) {
alert("Timeout expired.");
}
else {
alert("ERROR:" + err.message);
}
}
I have written these codelines. In browser on computers it will work perfectly, but if I install this app on my smartphone (Android, version 5.1.1) it does not work and I don't know why. It also not enters the error function on smartphone.
Do you know what to do?
this one may enter in to error function
function initiate_watchlocation() {
if (watchProcess == null) {
watchProcess = navigator.geolocation.watchPosition(onSuccess, onError);
}
}
var onSuccess = function(position) {
var myLatitude = position.coords.latitude;
var myLongitude = position.coords.longitude;
};
function onError(error) {
alert_box('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
consider running it in document.ready.
It is very special. When the app loads the site, it starts with the getCurrentPosition() function. Then I can step through, nothing happens. But after a few seconds (about 5) it will go through the success callback. And I save the results in $scope, because I work with AngularJS. But in the GUI I cannot recognize anything about the positions longitude and latitude.

Javascript function order

I want to execute functions in order but i constantly get 1,3,4,2 in console.Because of that ltt and lott remains 0 in function getDistanceFromLatLonInKm.Any ideas?Thanks in advance.
var ltt=0;
var lott=0;
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(ajmo);
console.log('1');
}
function ajmo(position){
console.log('2');
window.ltt=position.coords.latitude;
window.lott=position.coords.longitude;
document.write(window.ltt);
}
console.log('3');
document.write(window.ltt);
document.write("kurac:" + getDistanceFromLatLonInKm(45.332497,14.436384));
function getDistanceFromLatLonInKm(lat1,lon1){
console.log('4');
//second
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(ltt-lat1); // deg2rad below
var dLon = deg2rad(lott-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(ltt)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
The following changes will ensure that all console messages are in order 1,2,3,4
var ltt=0;
var lott=0;
if (navigator.geolocation){
console.log('1');
navigator.geolocation.getCurrentPosition(ajmo);
}
function ajmo(position){
console.log('2');
window.ltt=position.coords.latitude;
window.lott=position.coords.longitude;
document.write(window.ltt);
console.log('3');
document.write(window.ltt);
document.write("kurac:" + getDistanceFromLatLonInKm(45.332497,14.436384));
}
function getDistanceFromLatLonInKm(lat1,lon1){
console.log('4');
//second
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(ltt-lat1); // deg2rad below
var dLon = deg2rad(lott-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(ltt)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
The reason why they are being called out of order is because the method "geolocation.getCurrentPosition(success, error, options)" is asynchronous.
https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation
The (function)object AJMO that you are giving to it is actually used to describe the callback method. The script hits the line and sends an asynchronous request to the function, BUT it isn't going to wait for a response. The execution proceeds forward even though it hasn't heard back yet. The remaining lines are pretty simple with very low overhead so they resolve much, much quicker than the getCurrentPosition method. '2' is executed at the end, but this is only because the method finally "called back" to the success function you created, "AJMO".
If you want to make sure that the code is executed in order you could try this instead.
var ltt=0;
var lott=0;
function getDistanceFromLatLonInKm(lat1,lon1){
console.log('4');
//second
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(ltt-lat1); // deg2rad below
var dLon = deg2rad(lott-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(ltt)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function ajmo(position){
console.log('2');
window.ltt=position.coords.latitude;
window.lott=position.coords.longitude;
document.write(window.ltt);
console.log('3');
document.write("kurac:" + getDistanceFromLatLonInKm(45.332497,14.436384));
}
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(ajmo);
console.log('1');
}
This puts the calls to '2', '3', and '4' within the successful callback method while still exposing "getDistanceFromLatLonInKm" as a separate function if you need it for some other purpose.
You don't need to use global variables here. Simply include the call to getDistanceFromLatLonInKm within ajmo, and this will ensure that your code does things in the right order.
// call getLocation
getLocation();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ajmo);
}
}
function ajmo(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// don't use document.write - it's considered bad practice
// this will get access to an element with id="out"
var out = document.getElementById('out');
// now pass lat and lng as new parameters into getDistanceFromLatLonInKm
out.innerHTML = 'kurac:' + getDistanceFromLatLonInKm(45.332497, 14.436384, lat, lng);
}
// now use the lat/lng arguments instead of the global variables
function getDistanceFromLatLonInKm(lat_origin, lon_origin, lat_pos, lng_pos) {
var R = 6371;
var dLat = deg2rad(lat_pos - lat_origin);
var dLon = deg2rad(lng_pos - lng_origin);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat_origin)) * Math.cos(deg2rad(lat_pos)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}

Geolocation WatchPosition Distance Calculator

I am using geolocation to get the users current location and monitor it using the watchPosition method. However, is there a way of calculating the distance between the users starting position and current position? Below is my code:
var x = document.getElementById("info");
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition, showError, {
enableHighAccuracy: true,
maximumAge: 60000,
timeout: 27000
})
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
var flightPathCoordinates = [];
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude + "<br>Accuracy: " + position.coords.accuracy + "<br>Altitude: " + position.coords.altitude + "<br>Altitude Accuracy: " + position.coords.altitudeAccuracy + "<br>Heading: " + position.coords.heading + "<br>Speed: " + position.coords.speed + "<br>Speed (mph): " + position.coords.speed * 2.2369 + "<br>Speed (km): " + position.coords.speed * 3.6 + "<br>Timestamp: " + new Date(position.timestamp).toLocaleString() + "<br>Distance Travelled (km): " + calculateDistance(position.coords.latitude, position.coords.longitude, position.coords.latitude, position.coords.longitude);
// Distance Calculator
function calculateDistance(lat1, lon1, lat2, lon2) {
if(typeof (Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
}
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
lat = position.coords.latitude;
lon = position.coords.longitude;
latlon = new google.maps.LatLng(lat, lon)
mapholder = document.getElementById('mapholder')
var myOptions = {
center: latlon,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
}
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
Any help would be very much appreciated as I am quite new to this.
Thanks!
This has been adapted from the Google Maps API, and reworked to be independent of the library.
Example - calculate the distance from the center of New York City to the center of Philadelphia.
Fiddle for miles: http://jsfiddle.net/DXNzu/
Fiddle for kilometers: http://jsfiddle.net/DXNzu/1/
JS
function distanceFrom(points) {
var lat1 = points.lat1;
var radianLat1 = lat1 * (Math.PI / 180);
var lng1 = points.lng1;
var radianLng1 = lng1 * (Math.PI / 180);
var lat2 = points.lat2;
var radianLat2 = lat2 * (Math.PI / 180);
var lng2 = points.lng2;
var radianLng2 = lng2 * (Math.PI / 180);
var earth_radius = 3959; // or 6371 for kilometers
var diffLat = (radianLat1 - radianLat2);
var diffLng = (radianLng1 - radianLng2);
var sinLat = Math.sin(diffLat / 2);
var sinLng = Math.sin(diffLng / 2);
var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);
var distance = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));
return distance.toFixed(3);
}
var distance = distanceFrom({
// NYC
'lat1': 40.713955826286046,
'lng1': -74.00665283203125,
// Philly
'lat2': 39.952335,
'lng2': -75.163789
});
The result is 80.524 miles or 129.583 kilometers.
you can use Haversine formula
rad = function(x) {return x*Math.PI/180;}
distHaversine = function(p1, p2) { // Points are Geolocation.coords objects
var R = 6371; // earth's mean radius in km
var dLat = rad(p2.latitude - p1.latitude);
var dLong = rad(p2.longitude - p1.longitude);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
Two tips
typeof is not a function. Use it like this: typeof something
Do not put polyfills in listeners. you are repeating the polyfill action in every time listener fires.

About calculate distances between coordinates

I found this post:
Google Maps - How to get the distance between two point in metre?
I have the same problem, my variable "a" has the NaN value. I prefer not using google api if I can do it.
I am using the code in this web page: http://www.movable-type.co.uk/scripts/latlong.html
But my variables still return NaN...
This is my code:
function actualizaLimpieza(jsonData){ //jsonData keeps all points (lat&lon)
var latJSON;
var lonJSON;
var R = 6371; // km
var dLat;
var dLon;
var lat1;
var lat2;
var a;
var c;
var d;
latGPS = 43.466827534582606; //this are supossed to be gotten by gps, but for try...
lonGPS = -3.863614797592163;
for(i = 0; i < jsonData.length; i ++){
latJSON = jsonData[i].lng;
lonJSON = jsonData[i].lat;
dlat = toRad(latJSON-latGPS);
dlon = toRad(lonJSON-lonGPS);
latGPS = toRad(latGPS);
latJSON = toRad(latJSON);
a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(latGPS) * Math.cos(latJSON);
alert("a vale: " + a); //returns NaN
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
alert("c vale: " + c);
d = R * c;
alert("d vale: " + d);
if(d < 0,010){
alert("less than 10 meters");
}
}
}
function toRad(degrees){
return degrees * Math.PI / 180;
}
Should I do any more changes to get it working? Any script I should add? I haven't add anyone for this work.
Ok, I fail writing variables: dlat != dLat... Now it works more or less

Categories

Resources