Saving variables outside of navigator.geolocation.getCurrentPosition? (javascript)

前端 未结 2 2018
感情败类
感情败类 2021-01-05 11:50

I\'m trying to play with the scope of js to pull a variable out of navigator.geolocation.getCurrentPosition

var lat;
function callback (position) {
    lat =         


        
相关标签:
2条回答
  • 2021-01-05 12:34

    You can save your Position variable to input hidden field on document ready. After that, you can use jQuery to get back Geolocation value

    Javscript:

    <script>
    var lat;
    alert(lat); // this alerts null
    navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
    function callback (position) {
        jQuery('#pos_lat').val(position.coords.latitude);
    }
    </script>
    

    HTML:

        <input hidden id='pos_lat' value='' /> 
        //value = position latitude on load
    

    To get back value:

    jQuery('#pos_lat').val();
    
    0 讨论(0)
  • 2021-01-05 12:53

    You have to remember the async\ajax nature.

    this is the execution order of your code:

    var lat;
    alert(lat); // this alerts null
    navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
    function callback (position) {
        lat = position.coords.latitude;
    }
    

    This why you get null. async!, async! :)

    0 讨论(0)
提交回复
热议问题