Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 804
pol_guy Avatar asked Mar 18 '23 06:03

pol_guy


1 Answers

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

like image 52
Yoel Nunez Avatar answered Mar 20 '23 03:03

Yoel Nunez