I am trying to create a function that, using the geometry
library from google api, returns the distance between two coordinates (lat, lng).
The code below works in terms of finding the distance but I cannot find the way to return the result when the function is called. The result is always 0
.
To detect the current position I am using the cordova geolocation plugin.
How can alert the result from outside the function?
call Function:
alert(getLocationServices(51.583065, -0.019934)); // always 0
Main function:
function calculateDistanceCoords(myPosition, toPosition) {
var p1 = new google.maps.LatLng(myPosition[0], myPosition[1]);
var p2 = new google.maps.LatLng(toPosition[0], toPosition[1]);
var calcDistance = google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
var metersToMiles = (calcDistance * 0.000621371192).toFixed(2);
return metersToMiles;
}
function getLocationServices(lat, lng) {
var result = 0;
var onSuccess = function (position) {
var myLat = position.coords.latitude;
var myLng = position.coords.longitude;
var myPosition = [myLat, myLng];
var toPosition = [lat, lng];
result = calculateDistanceCoords(myPosition, toPosition);
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
result = -1;
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, {timeout: 3000});
return result; // always 0
}