1

My problem is that when I print the lat and long of my position to the console it works but when I pass them to my calculate function the console says they are undefined.

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } 
    else {
        location.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {

    console.log(position.coords.longitude); 

    var lat = position.coords.latitude;
    var lng = position.coords.longitude;

}

function calculate(lat,lng){
    var homeCoord = new Array();
    var awayCoord = new Array();
    console.log(lng);
    console.log(lat);

    homeCoord[0] = lat;
    homeCoord[1] = lng;
    awayCoord = myGeocodeFirst();

    var combinedLat = homeCoord[0]+awayCoord[0];
    var combinedLong = awayCoord[1]+homeCoord[1];

    console.log(combinedLat+" "+combinedLong);
}

Thanks for the help!

tnyN
  • 808
  • 6
  • 16

1 Answers1

1

Put it in the callback function:

function showPosition(position) {

    console.log(position.coords.longitude); 

    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    calculate(lat,lng);

}

function calculate(lat,lng){
    var homeCoord = new Array();
    var awayCoord = new Array();
    console.log(lng);
    console.log(lat);

    homeCoord[0] = lat;
    homeCoord[1] = lng;
    awayCoord = myGeocodeFirst();

    var combinedLat = homeCoord[0]+awayCoord[0];
    var combinedLong = awayCoord[1]+homeCoord[1];

    console.log(combinedLat+" "+combinedLong);
}
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • This works but not the way I wanted it to. I will just have to restructure my code. Thanks! – tnyN Sep 02 '14 at 22:52
  • 1
    Perhaps this might be interesting: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – geocodezip Sep 02 '14 at 23:09