当用户单击按钮然后重定向到新页面时,是否可以使用HTML5地理定位获取用户的纬度/经度?其中值将传递给PHP变量?
因此,如果用户在index.php
上,其中包含HTML5地理定位代码,则他们点击此按钮;
<span class="button get-my-location">My Location</span>
然后他们将被重定向到weather.php
,其中lat / long将存储在2个PHP变量$lat
和$long
这可能吗?我认为它需要基于AJAX?不幸的是,AJAX并不是我的强项。
任何帮助都会很棒
答案 0 :(得分:2)
很容易为用户获取经度和纬度,您需要将其分配给表单中的隐藏字段并将其提交到php页面网址或通过Javascript将其作为GET或POST发送
这是如何在获得位置后直接重定向用户的示例:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(redirectToPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function redirectToPosition(position) {
window.location='weather.php.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
</script>
</body>
</html>
PHP代码:
<?php
$lat=(isset($_GET['lat']))?$_GET['lat']:'';
$long=(isset($_GET['long']))?$_GET['long']:'';
//do whatever you want
?>
答案 1 :(得分:0)
getPosition.php,这是您的现有页面名称
<!DOCTYPE html>
<html>
<body ><!--onload="getLocation()" use it for on load page-->
<button onclick="getLocation()">Try It</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(redirectToPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function redirectToPosition(position) {
window.location='getPosition.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
</script>
<?php
echo $lat=(isset($_GET['lat']))?$_GET['lat']:'';
echo $long=(isset($_GET['long']))?$_GET['long']:'';
//do whatever you want
?>
</body>
</html>