Search code examples
phpopenstreetmapreverse-geocoding

Reverse geocoding using Nominatim in PHP


I am trying to perform some reverse geocoding in php. Unfortunately, I am getting an error.

$lon = 100.753;
$lat = 13.69362;

function getAddress($RG_Lat,$RG_Lon)
{
  $json = "http://nominatim.openstreetmap.org/reverse?format=json&lat=".$RG_Lat."&lon=".$RG_Lon."&zoom=27&addressdetails=1";
  $jsonfile = file_get_contents($json);
  $RG_array = json_decode($jsonfile,true);

  foreach ($RG_array as $name => $value)
  {
      if($name == "display_name")
      {
          $RG_address = $value;
          break;
      }
  }

  return $RG_address;
}

$addr = getAddress($lat,$lon);
echo "Address: ".$addr;

Here are the errors which I am getting.

<b>Warning</b>:  file_get_contents(http://nominatim.openstreetmap.org/reverse?format=json&amp;lat=13.69362&amp;lon=100.753&amp;zoom=27&amp;addressdetails=1): failed to open stream: Connection timed out in <b>/home/public_html/myapp/get_loc.php</b> on line <b>22</b><br />
<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/public_html/myapp/get_loc.php</b> on line <b>25</b><br />
<br />
<b>Notice</b>:  Undefined variable: RG_address in <b>/home/public_html/myapp/get_loc.php</b> on line <b>34</b><br />
Address: <br />

If I use below code in Angular then it is working fine.

showCountry($scope.latitude,$scope.longitude);
      function showCountry(lat, lon) {
              $.getJSON('//nominatim.openstreetmap.org/reverse?json_callback=?&format=json', {lat: lat, lon: lon}, function(data) {

                 console.log(data.address.town);
                 console.log('suburb- '+data.address.suburb);
                 console.log('county/district -'+data.address.county);
                 console.log('state - '+data.address.state);
                 console.log(data.address.postcode);
                  console.log(data.address.country);

             });
          }

I can't perform this action on the client side; that's the reason I need to do it in php.


Solution

  • You should use cURL (instead of file_get_contents()) to request the server with a user agent header, because OSM accepts only request with a valid user agent:

    $lon = 100.753;
    $lat = 13.69362;
    
    function getAddress($RG_Lat,$RG_Lon)
    {
      $json = "https://nominatim.openstreetmap.org/reverse?format=json&lat=".$RG_Lat."&lon=".$RG_Lon."&zoom=27&addressdetails=1";
    
      $ch = curl_init($json);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0");
      $jsonfile = curl_exec($ch);
      curl_close($ch);
    
      $RG_array = json_decode($jsonfile,true);
    
      return $RG_array['display_name'];
      // $RG_array['address']['city'];
      // $RG_array['address']['country'];
    }
    
    $addr = getAddress($lat,$lon);
    echo "Address: ".$addr;
    

    Output:

    Address: Short term parking, Sky Lane, สมุทรปราการ, จังหวัดสมุทรปราการ, 10520, ประเทศไทย


    Also, as @Kevin_Kinsey pointed out, you can also use file_get_contents() with stream_context_create():

    $opts = [
      'http' => [
        'method'=>"GET",
        'header'=>"User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) \r\n"
      ]
    ];
    $context = stream_context_create($opts);
    $jsonfile = file_get_contents($json, false, $context);