Search code examples
javascriptgeolocation

Javascript to log location into a file


I would like to use javascript to log Visitor's exact GEO location into a txt file (just cordination is OK). Any Ideas?


Solution

  • You could get user latitude and longitude with HTML5 getolocation and then send it with ajax to your save location api .

    <!DOCTYPE html>
    <html>
      <head>
       <script type="text/javascript">
         function initGeolocation()
         {
            if( navigator.geolocation )
            {
               // Call getCurrentPosition with success and failure callbacks
               navigator.geolocation.getCurrentPosition( success, fail );
            }
            else
            {
               alert("Sorry, your browser does not support geolocation services.");
            }
         }
    
         function success(position)
         {
    
             document.getElementById('long').value = position.coords.longitude;
             document.getElementById('lat').value = position.coords.latitude
         }
    
         function fail()
         {
            // Could not obtain location
         }
         var $locationForm = $("#LocationSaverForm");
         $locationForm.on("submit" , function(){
         var data = $(this)[0].serailize();
         $.ajax({
           type: "POST",
           url: "locationSaver.php",         
           data: data,
         });
      });
       </script>    
     </head>
    
     <body onLoad="initGeolocation();">
       <FORM NAME="rd" id="LocationSaverForm" METHOD="POST" ACTION="index.html">
         <INPUT TYPE="hidden" NAME="long" ID="long" VALUE="">
         <INPUT TYPE="hidden" NAME="lat" ID="lat" VALUE="">
       </FORM>
     </body>
    </html>
    

    then submit form and get information in backend.