如何使用谷歌地理编码API和PHP获取用户的当前位置


How to get a User's Current Location Using Google Geocode API and PHP

我创建了一个应用程序,作为数据收集的一部分,我想在用户使用 php 访问应用程序和网站时捕获用户的当前位置。

理想情况下,我想使这尽可能简单。 目前,我有以下脚本,但它有一个默认地址:

$fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
echo $json;
$string .= file_get_contents($fullurl); // get json content
$json_a = json_decode($string, true); //json decoder
echo $json_a['results'][0]['geometry']['location']['lat']; // get lat for json
echo $json_a['results'][0]['geometry']['location']['lng']; // get ing for json

我希望用户的当前位置取代加利福尼亚州山景城圆形剧场公园大道 1600 号。

任何帮助都非常感谢。

无法使用 PHP 获取用户位置,因为它在服务器端运行。您可以通过浏览器使用 javascript 获取用户位置。

下面是一个示例。在此示例中,我将代码分隔到两个文件中。一个用于使用PHP(geo坐标.php)处理和存储信息,另一个(HTML)用于收集地理编码信息(index.html),index.html。

您可以将这两个文件合并到索引中.php但为了简单起见,我会将它们分开。

地理坐标.php

<?php
if(isset($_POST['lat'], $_POST['lng'])) {
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];
    $url = sprintf("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s", $lat, $lng);
    $content = file_get_contents($url); // get json content
    $metadata = json_decode($content, true); //json decoder
    if(count($metadata['results']) > 0) {
        // for format example look at url
        // https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452
        $result = $metadata['results'][0];
        // save it in db for further use
        echo $result['formatted_address'];
    }
    else {
        // no results returned
    }
}
?>

索引.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Geocoding Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script>
  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(savePosition, positionError, {timeout:10000});
      } else {
          //Geolocation is not supported by this browser
      }
  }
  // handle the error here
  function positionError(error) {
      var errorCode = error.code;
      var message = error.message;
      alert(message);
  }
  function savePosition(position) {
            $.post("geocoordinates.php", {lat: position.coords.latitude, lng: position.coords.longitude});
  }
  </script>
</head>
<body>
    <button onclick="getLocation();">Get My Location</button>
</body>
</html>

请记住,在此示例中,一旦用户单击"获取我的位置",浏览器将提示用户允许地理位置。您也可以在页面加载后调用 getLocation 函数,但浏览器将始终请求用户的许可

您可以在 http://www.w3schools.com/htmL/html5_geolocation.asp 了解有关地理位置的更多信息

如前所述,PHP 是服务器端,所以我使用一个文件来获取 Long 和 Lat 坐标,然后将它们传递到我需要它们的地方......(不需要 API 密钥)

<?
session_start();
?>
<script>
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(getpos);
  } else {
  }
function getpos(position) {
           latx=position.coords.latitude;
           lonx=position.coords.longitude;
         // Show Lat and Lon 
           document.write('<div>Lat: '+latx+'<br> Long: '+lonx+'</div>');
         // or send them to use elsewhere
         //  location.href = '(your file name).php?latx='+latx+'&lonx='+lonx+'&shead=<? echo $shead ?>';
}
</script>