4

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.

Yoel Nunez
  • 2,108
  • 1
  • 13
  • 19
pol_guy
  • 457
  • 3
  • 8
  • 20
  • are you trying to get the current user location? ie: coordinates? if so what other information do you want to save about the location. ie: city, state, zip, etc – Yoel Nunez Jan 24 '15 at 05:35
  • Yoel, thanks so much for the detail check. It would be great to obtain all of that data for storage in a database - coordinates, city, state, and zip code. – pol_guy Jan 24 '15 at 05:42

2 Answers2

7

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

Yoel Nunez
  • 2,108
  • 1
  • 13
  • 19
  • 2
    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? – pol_guy Jan 24 '15 at 07:04
  • @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 http://stackoverflow.com/a/3885172/4114033 – Yoel Nunez Jan 24 '15 at 17:29
  • Nicely done +1. Fast and pretty reliable. Off by 2 houses in my test. Thanks! – ron tornambe Feb 27 '16 at 21:37
  • Can it work on localhost? I try doing that but its not working – Jaymin Dec 06 '16 at 13:23
0

As stated PHP is server side so I use a file to get the Long and Lat coordinates then pass them to where I need them....(No API Key is needed)

<?
session_start();
?>
<script>
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(getpos);
  } else {
  }
function getpos(position) {
           latx=position.coords.latitude;
           lonx=position.coords.longitude;
         // Show Lat and Lon 
           document.write('<div>Lat: '+latx+'<br> Long: '+lonx+'</div>');
         // or send them to use elsewhere
         //  location.href = '(your file name).php?latx='+latx+'&lonx='+lonx+'&shead=<? echo $shead ?>';
}
</script>

Paul T
  • 1