how to get current latitude and longitude using google map api in php?

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:

  1. 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>

 

  1. 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.";
}
?>

 

  1. Run the Application: Place both index.html and get_location.php files in the root directory of your web server. Open index.html in a web browser, click the "Get Location" button, and it should redirect you to get_location.php with the latitude and longitude parameters.

  2. 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.

Post your Answer