I am trying to make variables lat and loc global, but they are always zero.
var lat=0;
var loc=0;
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
});
alert(lat); // this eqals zero
That's an asynchronous call! Use this way:
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
alert (lat);
});
Background
When you are firing alert(lat)
, the getCurrentPosition()
wouldn't have fired and your value might have not set. If you wanna do something, put it or call it inside that function.
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
loc = position.coords.longitude;
// Something like this.
calculate (lat, loc);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.