1

I have some problems with the javascript for my user coordinates. In all examples they print an alert message on the return callback from geolocation, but I want to use the lat,long coordinates for printing or setting other values. What is the problem with this code? Can anyone be kind and explain: :)

<script type="text/javascript">
navigator.geolocation.getCurrentPosition(success);

function success(position) {
 var lat = position.coords.latitude;
 var long = position.coords.longitude;
}

document.write(lat);
</script>

and this is the errorcode with phonegap:

05-12 16:40:35.486: E/Web Console(15962): ReferenceError: Can't find variable: lat at file:///android_asset/www/showMap/showMap.html:31

Thanks

1

1 Answer 1

3

You've declared lat and long inside the success function, so that is where they are scoped to. You cannot access them outside the success function.

You could change your code to something like:

navigator.geolocation.getCurrentPosition(success);

function success(position) {
 var lat = position.coords.latitude;
 var long = position.coords.longitude;
 // lat is accessible inside "success", we can write out the variable here:
 document.write(lat);
}

Just to be clear, even if you made lat and long global here it wouldn't help you. success is executed asynchronously after getCurrentPosition has finished running.

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

1 Comment

@user1391179 the only correct solution is to move dependent code into success. Welcome to callbacks and asynchrony.

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.