由于 PHP 运行在服务器端,因此无法使用 PHP 获取用户位置。您可以通过浏览器使用javascript获取用户位置。
这是一个例子。在此示例中,我将代码分成两个文件。一种用于使用 PHP (geocoordinates.php) 处理和存储信息,另一种 (HTML) 用于收集地理编码信息 (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); // 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>
请记住,在此示例中,一旦用户单击“获取我的位置”,浏览器将提示用户允许地理定位。您也可以在页面加载后调用 getLocation 函数,但浏览器总是会请求用户的许可
您可以通过http://www.w3schools.com/htmL/html5_geolocation.asp了解更多有关地理定位的信息