Get location from latitude and longitude in PHP
Asked Answered
F

6

5

I want to get address, city, state and country in different variables so that I can display it separately but due to different latlong, somewhere I am getting whole address and somewhere only state and country, so I am not able to get a specific address due to changing latlong.

Here is my code:

$geoLocation=array();
$URL = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=8.407168,6.152344&sensor=false';
$data = file_get_contents($URL);
$geoAry = json_decode($data,true);
for($i=0;$i<count($geoAry['results']);$i++){
   if($geoAry['results'][$i]['types'][0]=='sublocality_level_1'){
     $address=$geoAry['results'][$i]['address_components'][0]['long_name'];
     $city=$geoAry['results'][$i]['address_components'][1]['long_name'];
     $state=$geoAry['results'][$i]['address_components'][3]['long_name'];
     $country=$geoAry['results'][$i]['address_components'][4]['long_name'];
     break;
  }
  else {
     $address=$geoAry['results'][0]['address_components'][2]['long_name'];
     $city=$geoAry['results'][0]['address_components'][3]['long_name'];
     $state=$geoAry['results'][0]['address_components'][5]['long_name'];
     $country=$geoAry['results'][0]['address_components'][6]['long_name'];
  }
}
$geoLocation = array(
  'city'=>$city,
  'state'=>$state,
  'country'=>$country,
  'address'=>$address
);
print_r($geoLocation);
Fibroid answered 14/4, 2015 at 9:45 Comment(0)
V
12

Try Below one:

<?php 
$geolocation = $latitude.','.$longitude;
$request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false'; 
$file_contents = file_get_contents($request);
$json_decode = json_decode($file_contents);
if(isset($json_decode->results[0])) {
    $response = array();
    foreach($json_decode->results[0]->address_components as $addressComponet) {
        if(in_array('political', $addressComponet->types)) {
                $response[] = $addressComponet->long_name; 
        }
    }

    if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
    if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; } 
    if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
    if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
    if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }

    if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
        echo "<br/>Address:: ".$first;
        echo "<br/>City:: ".$second;
        echo "<br/>State:: ".$fourth;
        echo "<br/>Country:: ".$fifth;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null'  ) {
        echo "<br/>Address:: ".$first;
        echo "<br/>City:: ".$second;
        echo "<br/>State:: ".$third;
        echo "<br/>Country:: ".$fourth;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
        echo "<br/>City:: ".$first;
        echo "<br/>State:: ".$second;
        echo "<br/>Country:: ".$third;
    }
    else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
        echo "<br/>State:: ".$first;
        echo "<br/>Country:: ".$second;
    }
    else if ( $first != 'null' && $second == 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
        echo "<br/>Country:: ".$first;
    }
  }
?>
Valerianaceous answered 14/4, 2015 at 11:4 Comment(5)
@SHAZ Its work with API key and SSL otherwise it works one or two times and then gives error "You have exceeded your daily request quota for this API."Bevbevan
@SHAZ what u think?Bevbevan
Yes, API key needed means you have to login into google's developer account and enable map service and get key for project u created. Also sensor deprecated now by googleValerianaceous
file_get_contents() has been disabled for security reasons.Stomodaeum
@MuhammedShihabudeenLabbaA you can use "CURL" instead of "file_get_contents()"Valerianaceous
S
2

Use Google Geocode API to get the location from latitude and longitude.

Here the simple PHP script for that.

$latitude = 'Insert Latitude';
$longitude = 'Insert Longitude';

$geocodeFromLatLong = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=false'); 
$output = json_decode($geocodeFromLatLong);
$status = $output->status;
$address = ($status=="OK")?$output->results[1]->formatted_address:'';

The above source code is found from here - Get Address from Latitude and Longitude using Google Maps API and PHP

Shady answered 12/4, 2016 at 7:46 Comment(0)
R
0

Check the Google Geocoding API here : https://developers.google.com/maps/documentation/geocoding

In your case, the location_type is set to "APPROXIMATE" It means that the returned result is not a precise geocode, which means that you will not have the whole address.

Rento answered 14/4, 2015 at 10:16 Comment(0)
G
0

I am using codeigniter and have similar requirements this is how i get it

    <script>
                    var lt=pos.lat;
                    var lon=pos.lng;
                    var current_lat=$("#current_lat").val(lt);
                    var current_long=$("#current_long").val(lon);

    </script>

HTML:

   <input type="hidden" id="current_lat" name="current_lat" value="<?php echo $this- 
 >session->userdata('current_lat');?>">
                        <input type="hidden" id="current_long" name="current_long" 
 value="<?php echo $this->session->userdata('current_long');?>">

Php:

        $current_long= $this->input->post('current_long');
        $current_lat=$this->input->post('current_lat');
        $newdata = array(

                   'current_lat'     => $current_lat,
                   'current_long'     => $current_long
               );

               $this->session->set_userdata($newdata);  

Guinn answered 13/10, 2019 at 8:57 Comment(0)
S
0

if you use laravel then it will usefull for you

    $latitude=26.12312;
    $longitude=83.77823;
    $geolocation = $latitude.','.$longitude;
    $response = \Http::get('https://maps.googleapis.com/maps/api/geocode/json', [
        'latlng' => $geolocation,
        'key' => 'api key',
        'sensor'    =>  false
    ]);
    $json_decode = json_decode($response);
    if(isset($json_decode->results[0])) {
        $response = array();
        foreach($json_decode->results[0]->address_components as $addressComponet) {
            $response[] = $addressComponet->long_name;
        }
        dd($response);
    }

please replace api key with your own

Sino answered 12/11, 2021 at 6:50 Comment(0)
K
-1

The above solutions will not work because google is now required API KEY to getting the data:

Here is the a simple function that will return lat, long along with google_place_id

function geoLocate($address)
{
    try {
        $lat = 0;
        $lng = 0;

        $data_location = "https://maps.google.com/maps/api/geocode/json?key=".$GOOGLE_API_KEY_HERE."&address=".str_replace(" ", "+", $address)."&sensor=false";
        $data = file_get_contents($data_location);
        usleep(200000);
        // turn this on to see if we are being blocked
        // echo $data;
        $data = json_decode($data);
        if ($data->status=="OK") {
            $lat = $data->results[0]->geometry->location->lat;
            $lng = $data->results[0]->geometry->location->lng;

            if($lat && $lng) {
                return array(
                    'status' => true,
                    'lat' => $lat, 
                    'long' => $lng, 
                    'google_place_id' => $data->results[0]->place_id
                );
            }
        }
        if($data->status == 'OVER_QUERY_LIMIT') {
            return array(
                'status' => false, 
                'message' => 'Google Amp API OVER_QUERY_LIMIT, Please update your google map api key or try tomorrow'
            );
        }

    } catch (Exception $e) {

    }

    return array('lat' => null, 'long' => null, 'status' => false);
}
Kokand answered 19/4, 2017 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.