HTML5地理位置,点击后将lat / long传递给PHP变量

问题描述 投票:0回答:2

当用户单击按钮然后重定向到新页面时,是否可以使用HTML5地理位置获取用户的纬度/经度,其中值将传递给PHP变量?

因此,如果用户在index.php上,其中包含HTML5地理位置代码,则他们点击此按钮;

<span class="button get-my-location">My Location</span>

然后它们将被重定向到weather.php,其中lat / long将存储在2个PHP变量$lat$long

这可能吗?我认为它需要基于AJAX?不幸的是,AJAX不是我的强项。

任何帮助都会很棒

php jquery ajax html5
2个回答
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

?>

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>
© www.soinside.com 2019 - 2024. All rights reserved.