How to get a User's Current Location Using Google Geocode API and PHP

34,519

There is no way to get the user location using PHP since it's running on the server side. You can get the user location using javascript through the browser.

Here is an example. In this example I separated the code in two files. One for processing and storing the information using PHP (geocoordinates.php) and another one (HTML) for collecting the geocoding informantion (index.html), index.html.

You could combine both files into index.php but I'll keep them separated for simplicity.

geocoordinates.php

<?php

if(isset($_POST['lat'], $_POST['lng'])) {
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];

    $url = sprintf("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s", $lat, $lng);

    $content = file_get_contents($url); // get json content

    $metadata = json_decode($content, true); //json decoder

    if(count($metadata['results']) > 0) {
        // for format example look at url
        // https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452
        $result = $metadata['results'][0];

        // save it in db for further use
        echo $result['formatted_address'];

    }
    else {
        // no results returned
    }
}

?>

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Geocoding Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script>
  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(savePosition, positionError, {timeout:10000});
      } else {
          //Geolocation is not supported by this browser
      }
  }

  // handle the error here
  function positionError(error) {
      var errorCode = error.code;
      var message = error.message;

      alert(message);
  }

  function savePosition(position) {
            $.post("geocoordinates.php", {lat: position.coords.latitude, lng: position.coords.longitude});
  }
  </script>
</head>
<body>
    <button onclick="getLocation();">Get My Location</button>
</body>
</html>

Keep in mind that in this example the once the user clicks "Get My Location" the browser will prompt the user to allow the geolocation. You could also call the getLocation function once the page loads, but the browser will always ask for the user's permission

You can learn more about geolocation at http://www.w3schools.com/htmL/html5_geolocation.asp

Share:
34,519
pol_guy
Author by

pol_guy

Updated on December 13, 2020

Comments

  • pol_guy
    pol_guy over 3 years

    I have created an app with and as part of data collection I would like to capture the user's current location when they access the app and website using php.

    Ideally, I want to make this as simple as possible. Currently, I have the following script, but it has a default address in it:

    $fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
    echo $json;
    $string .= file_get_contents($fullurl); // get json content
    $json_a = json_decode($string, true); //json decoder
    
    echo $json_a['results'][0]['geometry']['location']['lat']; // get lat for json
    echo $json_a['results'][0]['geometry']['location']['lng']; // get ing for json
    

    I would like the current location of the user to take the place of 1600 Amphitheater Parkway, Mountain View, CA.

    Any help is extremely appreciated.

  • pol_guy
    pol_guy over 9 years
    Yoel, the browser indicates that it's tracking my location, but I'm not able to echo the results of the location altogether or the $lng or $lat variables separately. Do you know what's up?
  • Yoel Nunez
    Yoel Nunez over 9 years
    @pol_guy I've just tried and experienced the same issue. I updated the answer with an error callback in case it fails to acquire your position. Apparently this is an know issue, check out stackoverflow.com/a/3885172/4114033
  • ron tornambe
    ron tornambe about 8 years
    Nicely done +1. Fast and pretty reliable. Off by 2 houses in my test. Thanks!
  • Jaymin
    Jaymin over 7 years
    Can it work on localhost? I try doing that but its not working