var alt, lat, long;
function onSuccess(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
alt = position.coords.altitude;
}
function onError(error) {
myApp.alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n', main_title);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
alert(long + ' ' + lat);
hi, i'm new to java script. please help me to get out coordinations from above method. alert just undefined.
The problem is the placement of your alert. The alert needs to go in the onSuccess callback method. Here's how JavaScript interprets your code.
See the problem? The alert happens right away while geolocation is happening asynchronously. It might seem like geolocation happens instantly but as far as the flow of code is concerned, it happens just a bit in the future after the rest of our code has finished running.
Try this code instead:
var alt, lat, long;
function onSuccess(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
alt = position.coords.altitude;
allert(long + ', ' + lat);
}
function onError(error) {
myApp.alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n', main_title);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
You should define OnSuccess
function and get the latitude
and longitude
;
function onSuccess(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
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.