Search code examples
javascriptjqueryhtmlgeolocation

div doesn't update on Calling watchLocation


Below is the HTML5 code for finding updated geolocation. Latitude and Longitude values pops in alert box. But, the value cannot be assigned to the div using $(id).html(value); . I am using watchPosition() function.

   <html>
     <head>   
      <script type="text/javascript">
         var watchID;
         var geoLoc;

         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
             $("#lat").html(latitude);
             $("#long").html(longitude);
             }         

         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }

            else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }

         function getLocationUpdate(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
            }

            else{
               alert("Sorry, browser does not support geolocation!");
            }
         }
      </script>

   </head>
   <body>

      <form>
         <input type="button" onclick="getLocationUpdate();" value="Watch Update"/>
         Latitude : <div id="lat"></div>
         Longitude : <div id="long"></div>
       </form>


   </body>
</html>

Solution

  • When you use alert() it stops all further execution of your code, so move the alert() below your lines assigning the value to the div and that should solve your problem.

    $("#lat").html(latitude);
    $("#long").html(longitude);
    alert("Latitude : " + latitude + " Longitude: " + longitude);