0

I'm facing issues getting value of a variable from another function. I'm trying to get the distance of the place from current position in google maps, but using Haversine Formula of calculating distance.

My HTML:

<p>
  <script>
  lat = "<?php echo $atm_row_data->latitude;?>";
  lng = "<?php echo $atm_row_data->longitude;?>";
  dist = getDistance(lat, lng);
  document.write(dist);
  </script>
</p>

My JavaScript:

var curPosition;
var lat, lng;

/**** get current position ****/
function getPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showCurrentPosition);
    } else {
        alert('Geolocation is not supported by this browser.');
    }
}

function showCurrentPosition(position) {
    lat = position.coords.latitude;
    lng = position.coords.longitude;
    curPosition = new google.maps.LatLng(lat, lng);
    console.log('curPosition: '+curPosition); <--- this works
}

/******** Haversine Formula of Getting Distance ********/
var rad = function(x) {
  return x * Math.PI / 180;
};

function getDistance(lt, lg) {
    console.log(curPosition); <--- this shows undefined
    var p1 = curPosition;
    var R = 6378137; // Earth’s mean radius in meter
    var dLat = rad(lt - p1.lat());
    var dLong = rad(lg - p1.lng());
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(lt)) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    if (d >= 1000)
        return Math.round( (d / 1000) * 100) / 100 + "Km";
    else
        return Math.round( (d * 100) / 100) + "m";
};
/******** END Haversine Formula of Getting Distance ********/

Where am I going wrong?

Any help is appreciated...

8
  • 1
    Check the console. Are you getting errors? Is it that you're not getting the correct answer? Nothing? Commented Sep 1, 2015 at 17:51
  • 1
    I guess you never call showCurrentPosition, so the curPosition remains undefined. Commented Sep 1, 2015 at 17:51
  • The problem is most likely variable scope. You are trying to access a variable outside scope. Try defining curPosition in the beginning outside any functions. Commented Sep 1, 2015 at 17:53
  • Console throws: undefined Uncaught TypeError: Cannot read property 'lat' of undefined Commented Sep 1, 2015 at 17:56
  • 1
    @h4kl0rd but getPosition() is not called before calling getDistance(). Commented Sep 1, 2015 at 17:59

2 Answers 2

1

Knowing the google api, , navigator.geolocation has a callback, so showcurrentPostion is the callback function, but the thing is u never call getPosition() <--

function getDistance(lt, lg) {
    console.log(curPosition); <--- this shows undefined <---- so this will always be undefined
    var p1 = curPosition;
    var R = 6378137; // Earth’s mean radius in meter
    var dLat = rad(lt - p1.lat());
    var dLong = rad(lg - p1.lng());
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(lt)) *  <--- see comment
    Math.sin(dLong / 2) * Math.sin(dLong / 2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    if (d >= 1000)
        return Math.round( (d / 1000) * 100) / 100 + "Km";
    else
        return Math.round( (d * 100) / 100) + "m";
};
  • comment: <------ p1 curposition gets an google maps object with lat and long where i know that lat() is not a function so this will fail so even when u get the current position the function above (getDistance()) will fail

Call getPosition first() <--- u need to get the position

edit: i see that u can call console.log and you say it works, so i think its a scoping issue,

I made an example for you -> http://codepen.io/anon/pen/qOBMPj i'm not able to render the googlemap within the pen, but u can look at the source, on how its done. hope this helps you.

so in order to do this calculation u dont really need google maps u just need the first/ and second coords, but its fun to do something with on on the google map:)

Sign up to request clarification or add additional context in comments.

14 Comments

Can we initiate a chat?
ive updated my answer, the pen will give you the distance from your current location, to amsterdam :D, copy the source to see how its done, Ive added the correct formula, with the link from they guy who made all the mathematical calculations (Chris Veness), my code shows u how to calculate the position from point to point, i did not copy all your code into it, only the code that was needed, i namespaced the functions within Maps {} if this helps , please accept as "ANSWER"
thanks for your pen, I went through it, but it works for one location not multiple. I'm looping through lots of locations and passing their lats and longs to getDistance() to get distance from my current location to these locations.
@h4kl0rd, then u should u pass the currentlocation and location u wish to calculate the distance to to the getdistance function, from ur loop, so u can get it for all locations. just add it to ur loop , and store it somewhere. - if it works for one, it will work for many
i didnt have the time to debug your code, but by taking a quick look i think this is undefined within the succes, your within the callback, so its not the same scope, so line 72: navigator.geolocation.getCurrentPosition(this.success, this.fail); should be navigator.geolocation.getCurrentPosition(this.success.bind(this), this.fail.bind(this)); in order for this success to have the same scope.
|
1

In your script tags, your only call getDistance(lat,lng), but showCurrentPosition(position) is never called! So the variable curPosition is undefined, because it is not defined yet!

You need to call showCurrentPosition(position) for the variable curPosition to hold a value.

Perhaps calling getPosition() at the beginning of your getDistance() function could solve the problem, as it seems to call showCurrentPosition.


Alternative to show the position in HTML (this is just a quick snippet, you can adapt it to whatever you like):

function getPositionHTML() {
    navigator.geolocation.getCurrentPosition(function(pos) {
        curPosition = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
    });
    return curPosition;
}

It basically does the same thing as your other function, but it relies on the Single Reponsibility Principle, so once you called this function you can manipulate curPosition however you want.

3 Comments

I have called the getPosition() in initialize() function and tried to call it before getDistance() but still throws undefined. I just want to display the distance in the html. Maybe there's another way.
I tried making the edits but still returning undefined. It only works if I place return curPosition inside the navigator.geolocation..., which then returns undefined when calling outside the function or from another function.
@h4kl0rd Then you have two choices: You either do the UI modifications within that function (getPositionHTML), or you use a Promise object to make sure the getCurrentPosition function has been successfully completed and use a then to do the UI modification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.