如何使用Google地理编码API和PHP获取用户的当前位置 [英] How to get a User's Current Location Using Google Geocode API and PHP

查看:198
本文介绍了如何使用Google地理编码API和PHP获取用户的当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  $ fullurl =http:// maps ?.googleapis.com /地图/ API /地理编码/ JSON地址= 1600 + +剧场大道,+山+视图,+ CA&安培;传感器=真; 
echo $ json;
$ string。= file_get_contents($ fullurl); //获取json内容
$ json_a = json_decode($ string,true); // json解码器

echo $ json_a ['results'] [0] ['geometry'] ['location'] ['lat']; //获取拉斯的json
echo $ json_a ['results'] [0] ['geometry'] ['location'] ['lng']; //获取为json

我想用户的当前位置代替1600 Amphitheatre Parkway,Mountain View,CA。



非常感谢任何帮助。 >

由于PHP在服务器端运行,因此无法使用PHP获取用户位置。您可以通过浏览器使用JavaScript获取用户位置。



以下是一个示例。在这个例子中,我将代码分成两个文件。一个用于使用PHP(geocoordinates.php)处理和存储信息,另一个用于收集地理编码信息(index.html),index.html。



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

geocoordinates.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); //获取json内容

$ metadata = json_decode($ content,true); // json解码器

if(count($ metadata ['results'])> 0){
//格式示例请看url
// https:/ /maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452
$ result = $ metadata ['results'] [0];

//将其保存在数据库中以供进一步使用
echo $ result ['formatted_address'];

}
else {
//无结果返回
}
}

?>

index.html

 <!DOCTYPE html> 
< html>
< head>
< meta charset =utf-8>
< title>地理编码网页< /标题>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js>< / script>
< script>
函数getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(savePosition,positionError,{timeout:10000});
} else {
//这个浏览器不支持地理定位
}
}

//在这里处理错误
function positionError (错误){
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();>获取我的位置< / button>
< / body>
< / html>

请注意,在此示例中,一旦用户单击Get My Location,浏览器将提示用户允许地理位置。您也可以在页面加载时调用 getLocation 函数,但浏览器将始终询问用户的权限。

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


I have created an app with and as part of data collection I would like to capture the user's current location when they access the app and website using php.

Ideally, I want to make this as simple as possible. Currently, I have the following script, but it has a default address in it:

$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

I would like the current location of the user to take the place of 1600 Amphitheater Parkway, Mountain View, CA.

Any help is extremely appreciated.

解决方案

There is no way to get the user location using PHP since it's running on the server side. You can get the user location using javascript through the browser.

Here is an example. In this example I separated the code in two files. One for processing and storing the information using PHP (geocoordinates.php) and another one (HTML) for collecting the geocoding informantion (index.html), index.html.

You could combine both files into index.php but I'll keep them separated for simplicity.

geocoordinates.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
    }
}

?>

index.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>

Keep in mind that in this example the once the user clicks "Get My Location" the browser will prompt the user to allow the geolocation. You could also call the getLocation function once the page loads, but the browser will always ask for the user's permission

You can learn more about geolocation at http://www.w3schools.com/htmL/html5_geolocation.asp

这篇关于如何使用Google地理编码API和PHP获取用户的当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆