GpsGetCoords

From WebOS101

Jump to: navigation, search

Simple GPS getCoordinates

The docs at palm are actually pretty complete on the GPS service - this simple script will get your coordinates:

MyAssistant.prototype.someButtonHandler = function(event) {
 
this.controller.serviceRequest('palm://com.palm.location', {
method: 'getCurrentPosition',
parameters: {
maximumAge: 5, // number of seconds that cached coord can be used before new one's acquired
// default is 0, which will automatically retrieve a new coordinate object
accuracy: 2, // 2 is default - gets your coords within 350 meters
responseTime: 2 // 2 is the default - between 5 and 20 seconds
 
},
onSuccess: this.handleServiceResponse.bind(this),
onFailure: this.handleGpsError.bind(this)
});
};

Calculating Distances

The Haversine formula will calculate the distance between your gps coords and some other location.

This code is courtesy of the nice folks at http://www.movable-type.co.uk/scripts/latlong.html. In this example, I have an array (this.myPlaces) of locations complete with their own lat/lon coordinates. I will be calculating the distances between each location and my own:

MyAssistant.prototype.handleServiceResponse = function(event) {
 
 
for (i = 0; i < this.myPlaces.length; i++) {
var lat2 = this.myPlaces[i].lat;
var lon2 = this.myPlaces[i].lon;
 
var lat1 = event.latitude; // my gps latitude returned in the coordinate object
var lon1 = event.longitude; // my gps longitude returned in the coordinate object
 
// And now, we Haversine - I'm calculating the distance in miles:
 
var toRad = Math.PI / 180;
 
var R = 3959; // radius of the earth in miles (to return distance in km, use 6371)
 
var dLat = (lat2 - lat1) * (Math.PI / 180);
var dLon = (lon2 - lon1) * (Math.PI / 180);
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.asin(Math.sqrt(a));
var d = R * c;
 
this.distance = Math.round(d); // finally we have the distance
this.myPlaces[i].dist = this.distance; // put the new value into the array
 
}
 
// now we can call a sort function:
this.myPlaces.sort(this.sortby);
};
 
// this sorts our array ascending by distance:
 
MyAssistant.prototype.sortby = function(a,b){
 
a = a.dist;
b = b.dist;
a = parseInt(a, 10);
b = parseInt(b, 10);
return a-b;
};

Now we have an array full of locations with the distance (as the crow flies) from our newly created GPS coords.

Personal tools