Javascript 将位置记录到文件中

Javascript to log location into a file

我想使用 javascript 将访问者的确切 GEO 位置记录到一个 txt 文件中(只需协调即可)。有什么想法吗?

您可以使用 HTML5 getolocation 获取用户 latitudelongitude,然后使用 ajax 将其发送到您的保存位置 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>

然后提交表单并在后台获取信息。

Geolocation.getCurrentPosition()可以给出位置坐标。

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

这里是 Whosebug post 使用 nodeJS fs 模块在文件上写入数据:Writing files in Node.js

结合 Geolocation.getCurrentPosition() 和 fs 模块坐标可以保存在文本文件中。