To get the current latitude and longitude using the Google Maps Geolocation API in PHP, you can use a combination of HTML5 Geolocation in the frontend and PHP to process the obtained data. Here's a simple example:
- Create an HTML Form: Create an HTML form that includes a button triggering the geolocation retrieval. Save it as
index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Current Location</title>
</head>
<body>
<h1>Get Current Location</h1>
<button onclick="getLocation()">Get Location</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
// Pass the obtained latitude and longitude to a PHP script
window.location.href = `get_location.php?lat=${position.coords.latitude}&lng=${position.coords.longitude}`;
}
</script>
</body>
</html>
- Create a PHP Script to Process Coordinates: Create a PHP script (
get_location.php
) to handle the coordinates sent from the frontend and display them:
<?php
if (isset($_GET['lat']) && isset($_GET['lng'])) {
$lat = $_GET['lat'];
$lng = $_GET['lng'];
echo "Latitude: {$lat}, Longitude: {$lng}";
} else {
echo "Error: Coordinates not provided.";
}
?>
-
Run the Application: Place both
index.html
andget_location.php
files in the root directory of your web server. Openindex.html
in a web browser, click the "Get Location" button, and it should redirect you toget_location.php
with the latitude and longitude parameters. -
Display the Coordinates: The
get_location.php
script will receive the latitude and longitude as parameters and echo them. You can modify this script to perform additional actions with the obtained coordinates.