【发布时间】:2013-10-24 17:27:06
【问题描述】:
我有一个 PHP 脚本,它使用 Google Maps API 和 JavaScript 地理定位系统计算距离。
我想在我的 PHP 代码中获取当前用户的坐标,例如:
$user_location = array(latitude, longitude);
到目前为止,我正在尝试这样的事情:
location.php:
$contents = file_get_contents('user_loc.html');
if ($contents != "false") {
$user_location = explode(',', $contents);
}
// Do stuff with coordinates
user_loc.html:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(
function (position) {
console.log(position.coords.latitude);
document.write(position.coords.latitude + ',' + position.coords.longitude);
},
function (error) {
document.write("false");
},
{
timeout: (5 * 1000),
maximumAge: (1000 * 60 * 15),
enableHighAccuracy: true
}
);
</script>
</head>
<body>
</body>
</html>
我很确定这不是最好的方法。有什么建议吗?
【问题讨论】:
-
您必须使用 js 在客户端运行才能获取地理位置,然后将其发送回服务器。或者您可以仅根据请求者的 ip 获取地理位置,但这可能不太可靠。
-
file_get_contents 将获得文件的字符串输出,而不是您要查找的结果。您需要访问该页面,然后在该页面上您可以使用 lat 和 long 对 location.php 进行 POST 并根据需要进行处理
标签: javascript php geolocation navigator