Javascript 如何使用 Google Geocode API 和 PHP 获取用户的当前位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28122499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a User's Current Location Using Google Geocode API and PHP
提问by pol_guy
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.
我创建了一个应用程序,作为数据收集的一部分,我想在用户使用 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.
我希望用户的当前位置代替 1600 Amphitheatre Parkway, Mountain View, CA。
Any help is extremely appreciated.
非常感谢任何帮助。
回答by Yoel Nunez
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.
由于 PHP 在服务器端运行,因此无法使用 PHP 获取用户位置。您可以通过浏览器使用 javascript 获取用户位置。
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.
这是一个例子。在这个例子中,我将代码分成了两个文件。一个用于使用 PHP (geocoordinates.php) 处理和存储信息,另一个 (HTML) 用于收集地理编码信息 (index.html),index.html。
You could combine both files into index.php but I'll keep them separated for simplicity.
您可以将这两个文件合并到 index.php 中,但为了简单起见,我会将它们分开。
geocoordinates.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
}
}
?>
index.html
索引.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 getLocationfunction once the page loads, but the browser will always ask for the user's permission
请记住,在此示例中,一旦用户单击“获取我的位置”,浏览器将提示用户允许地理定位。您也可以在页面加载后调用getLocation函数,但浏览器将始终请求用户的许可
You can learn more about geolocation at http://www.w3schools.com/htmL/html5_geolocation.asp
您可以在http://www.w3schools.com/htmL/html5_geolocation.asp了解有关地理定位的更多信息
回答by Paul T
As stated PHP is server side so I use a file to get the Long and Lat coordinates then pass them to where I need them....(No API Key is needed)
如前所述,PHP 是服务器端,所以我使用一个文件来获取经纬度坐标,然后将它们传递到我需要的地方......(不需要 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>

