0

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
}
SNos
  • 3,430
  • 5
  • 42
  • 92
  • You can't return the `result` set by the `onSuccess` callback bassed to `getCurrentPosition`, like that. – Cerbrus Sep 26 '16 at 11:18
  • Thank you. And what is the best approach in order to achieve what I need? – SNos Sep 26 '16 at 11:19
  • 1
    Pass a callback to `getLocationServices`. instead of `result = calc...`, do `myCallback(calc...)` – Cerbrus Sep 26 '16 at 11:20
  • Any example? I don't understand where to get `mycallback` – SNos Sep 26 '16 at 11:26
  • 1
    You need to pass a extra function to do something with the results, to `getLocationServices`: `getLocationServices(lat, lng, myCallback)` – Cerbrus Sep 26 '16 at 11:28
  • Ok, then I wrap `myCallback(calculateDistanceCoords(myPosition, toPosition);)` ... How do I return my callback ? ` alert(getLocationServices(51.583065, -0.019934).myCallback); ` – SNos Sep 26 '16 at 11:37
  • SNos, did you read the question I marked this one as a duplicate of? – Cerbrus Sep 26 '16 at 11:41
  • Sorry, yes just seen the page and found out the answer. Quite simple actually. Thank you for your help. `getLocationServices(51.583065, -0.019934, function (r) { alert(r) });` – SNos Sep 26 '16 at 11:42

0 Answers0