Saving variables outside navigator.geolocation.getCurrentPosition? (Javascript)

I'm trying to play with js volume to pull a variable from navigator.geolocation.getCurrentPosition

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

The above code cannot store position.coords.latitude in lat variable due to scope. Is there any way to do this?

+6
source share
2 answers

You must remember the nature of async \ ajax.

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; } 

That is why you get null. async! , async! :)

+2
source

You can save your Position variable to enter a hidden field in the finished document. After that, you can use jQuery to return the 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 return a value:

 jQuery('#pos_lat').val(); 
0
source

Source: https://habr.com/ru/post/911995/


All Articles