当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - using coordinate variables

问题描述:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: