Jeżeli nie używasz w projekcie jQuery podajesz poniższy kod w <head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
Następnie w <form> wrzucasz:
<input type="hidden" name="latitude" /> <input type="hidden" name="longitude" />
Bazując na poście ze StackOverflow
http://stackoverflow.com/a/39367531/2621852 wklejasz na końcu strony w <body>:
<script type="application/javascript">
$(document).ready(function () {
var apiGeolocationSuccess = function(position) {
setCoordsToForm(position);
};
var setCoordsToForm = function (position) {
$('input[name=latitude]').val(position.coords.latitude);
$('input[name=longitude]').val(position.coords.longitude);
};
var tryAPIGeolocation = function() {
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDCa1LUe1vOczX1hO_iGYgyo8p_jYuGOPU", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
});
};
var browserGeolocationSuccess = function(position) {
setCoordsToForm(position);
};
var browserGeolocationFail = function(error) {
switch (error.code) {
case error.TIMEOUT:
alert("Browser geolocation error !\n\nTimeout.");
break;
case error.PERMISSION_DENIED:
if(error.message.indexOf("Only secure origins are allowed") == 0) {
tryAPIGeolocation();
}
break;
case error.POSITION_UNAVAILABLE:
alert("Browser geolocation error !\n\nPosition unavailable.");
break;
}
};
var tryGeolocation = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
browserGeolocationSuccess,
browserGeolocationFail,
{maximumAge: 50000, timeout: 20000, enableHighAccuracy: true});
}
};
tryGeolocation();
});
Po wysłaniu formularza pola są dostępne w PHP:
<?php
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];