在文件中保存HTML5位置信息

时间:2015-02-06 09:07:31

标签: php html5 file location geo

我尝试使用当前脚本执行以下操作:

  • 当访问者点击"接受检测我的​​位置"
  • 时,将Google地理位置信息保存在文件中
  • 使用信息输出Google地图网址



<!DOCTYPE html>
<html>
  <head>
    <style>
      #tripmeter {
        border: 0px double black;
        padding: 0px;
        margin: 0px 0;
      }
      
      p {
        color: #222;
        font: 14px Arial;
      }
      
      span {
        color: #00C;
      }
    </style>
  </head>
  <body>
    <div id="tripmeter">
      <p>
        Starting Location (lat, lon):<br/>
        <span id="startLat">???</span>&deg;, <span id="startLon">???</span>&deg;
      </p>
      <p>
        Current Location (lat, lon):<br/>
        <span id="currentLat">???</span>&deg;, <span id="currentLon">???</span>&deg;
      </p>
      <p>
        Distance from starting location:<br/>
        <span id="distance">0</span> km
      </p>
    </div>
    <script>
      window.onload = function() {
        var startPos;
      
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            startPos = position;
            document.getElementById("startLat").innerHTML = startPos.coords.latitude;
            document.getElementById("startLon").innerHTML = startPos.coords.longitude;
          }, function(error) {
            alert("Error occurred. Error code: " + error.code);
            // error.code can be:
            //   0: unknown error
            //   1: permission denied
            //   2: position unavailable (error response from locaton provider)
            //   3: timed out
          });
      
          navigator.geolocation.watchPosition(function(position) {
            document.getElementById("currentLat").innerHTML = position.coords.latitude;
            document.getElementById("currentLon").innerHTML = position.coords.longitude;
            document.getElementById("distance").innerHTML =
              calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
                                position.coords.latitude, position.coords.longitude);
          });
        }
      };
      
      // Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
      // http://www.movable-type.co.uk/scripts/latlong.html
      // Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
      function calculateDistance(lat1, lon1, lat2, lon2) {
        var R = 6371; // km
        var dLat = (lat2-lat1).toRad();
        var dLon = (lon2-lon1).toRad();
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
                Math.sin(dLon/2) * Math.sin(dLon/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        return d;
      }
      Number.prototype.toRad = function() {
        return this * Math.PI / 180;
      }
    </script>
  </body>
</html>

    <meta charset="utf-8"/> 
    
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
</head>
 
<body>
    <div id="pos" style="width:800px; height:600px;">
        Detection Location..
    </div>
    
    <script>
        function initialize(coords) {
            var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("pos"), myOptions);
            
            var marker = new google.maps.Marker({
                position: latlng, 
                map: map, 
                title: "You"
            }); 
        }
  
        navigator.geolocation.getCurrentPosition(function(position){ 
            initialize(position.coords);
        }, function(){
            document.getElementById('pos').innerHTML = 'Failed to detect Location.';
        });
    </script>

<?php
$dns = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$rand2 = time();
$port= htmlspecialchars(
$_SERVER['REMOTE_PORT']);
$browser= htmlspecialchars(
$_SERVER['HTTP_USER_AGENT']);
$ausgabe="• I WANT TO SAVE THE GOOGLE MAPS URL WITH THE DETECTED LOCATION •";
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
?>

</body>
</html>
&#13;
&#13;
&#13;

任何人都有好主意? :)

1 个答案:

答案 0 :(得分:1)

如果您想将经度和纬度保存到文件中(如果您甚至允许这样做,请查看Google API使用条款),您必须首先获取坐标,然后通过AJAX将它们发送到您的服务器。

以下示例不是&#34;复制/粘贴&#34;材料,因为我没有尝试过。将它们作为一般准则使用。

首先,您需要创建一个脚本,它将获得坐标:

<html>
<head>    
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>

<body>
    <div id="pos" style="width:800px; height:600px;">
        Detection Location..
    </div>

    <script>
    $(function(){
            function initialize(coords) {
                $.ajax({
                   url: 'saveLocation.php',
                   data: {
                        longitude:coords.longitude,
                        latitude:coords.latitude
                        },
                   error: function() {
                      $('#pos').html("Could not save location");
                   },
                   success: function(data) {
                      $('#pos').html("Location saved successfully");
                   },
                   type: 'POST'
                });
            }

            navigator.geolocation.getCurrentPosition(function(position){ 
                initialize(position.coords);
            }, function(){
                $('#pos').html('Failed to detect Location.');
            });
    });
    </script>
    </body>
    </html>

在您的服务器上,您需要一个PHP脚本&#34;&#34; saveLocation.php&#34;:

<?php
$ausgabe=$_POST['longitude'].":".$_POST['latitude'];
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);

echo json_encode(array("success"=>"true"));
?>

我使用jQuery来简化一些常规的东西,比如通过AJAX发送数据或更改元素的内部HTML。

同样,此代码未处于工作状态。如果你只是复制/粘贴它将无法正常工作