Dean Elliott
Dean Elliott

Reputation: 729

HTML5 geolocation, pass lat/long to PHP variable on click

Is it possible to get the latitude / longitude of a user using HTML5 geolocation when they click a button and then redirect to a new page where the values will have been passed to PHP variables?

So if a user is on index.php, which contains the HTML5 geolocation code, and they click on this button;

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

They'll then be redirected to weather.php where their lat/long will be stored in 2 PHP variables $lat and $long

Is this possible? I assume it would need to be AJAX based? Unfortunately AJAX isn't my strong suit.

Any help would be great

Upvotes: 2

Views: 14478

Answers (2)

Amranur Rahman
Amranur Rahman

Reputation: 1123

getPosition.php this is your exiting page name

<!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>

Upvotes: 1

Devy
Devy

Reputation: 248

It's easy to get longitude and latitude for user and you will need to assign it to hidden field in form and submit it to the php page url or send it as GET or POST by Javascript

This is example how to redirect user directly after having his location:

<!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 CODE:

<?php

$lat=(isset($_GET['lat']))?$_GET['lat']:'';
$long=(isset($_GET['long']))?$_GET['long']:'';

//do whatever you want

?>

Upvotes: 6

Related Questions