Julien Julien - 7 months ago 100
PHP Question

Save Geolocation in php variables

i want to save the latitude & longitude into php variables
For example i want a output like this:

<?php echo $latitude ?>


Here's the script for capturing the location(from w3schools)

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>


But i really dont know how to save the coords inside this funktion :/

Answer

JavaScript executes in browser after the PHP execution completes in server, so you will never be able to use JavaScript variable inside PHP.

However if you intend to save geolocation somewhere you can make an ajax call after geocoder executes to save location latitude and longitude to your database by user id or any parameter you are capturing.

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
    $.ajax({
        // you ajax code here
    });
}