简体   繁体   中英

how to get coordinate out from Geo-location method

        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.

  1. It creates the variables alt, lat, and long
  2. It creates the functions onSuccess and onError
  3. It calls the navigator.geolocation.getCurrentPosition method, handing it our onSuccess and onError callbacks
  4. Geolocation happens asynchronously
  5. Alerts long and lat
  6. Geolocation finishes and calls either onSuccess or onError
  7. If onSuccess was called, long and lat values are set into their corresponding variables.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM