adnane adnane - 6 months ago 26
jQuery Question

JS Geolocation and Storage

this is my code
http://jsfiddle.net/#&togetherjs=mjFbd89fzF

$(document).ready(function () {

if (navigator.geolocation) {

}
if (typeof (localStorage) != "undefined") {

navigator.geolocation.getCurrentPosition(function (position) {
localStorage.setItem('latitude', position.coords.latitude);
localStorage.setItem('longitude', position.coords.longitude);
});

$('#location').innerHTML = localStorage.getItem('latitude') + ' ' + localStorage.getItem('longitude');

}
});


here's the HTML

<BODY>
<h1>you're here</h1>

<h2 id="location"></h2>

</BODY>


i get prompted to share my location but the h2 tag doesn't get updated even if the position is stored in localstorage

Answer

getCurrentPosition is asynchronous function and will executed after $('#location')., you can store it in local storage but this data will be available after second page load, you can set $('#location') in getCurrentPosition or you can use Deferred.

#1
$(document).ready(function () {
 if (navigator.geolocation) {}

  navigator.geolocation.getCurrentPosition(function (position) {
   $('#location').html(position.coords.latitude + ' ' + position.coords.longitude);
  });
});

#2
$(document).ready(function () {
  var d = $.Deferred();

  if (navigator.geolocation) {}

  navigator.geolocation.getCurrentPosition(function (position) {
    d.resolve(position.coords.latitude, position.coords.longitude);
  });

  d.done(function(latitude, longitude) { 
    $('#location').html(latitude + ' ' + longitude);
  });
});

Example