How to get geo data using address in google map

21:20

GEO FIELDS

we are getting following geo data by using address in google map
  • latitude
  • longitude
  • country long name
  • country short name
  • state long name
  • state short name
So we can achieve this functionality by using PHP Curl please paste following function in your file.
function getting_address($address)
{
 $url = "http://maps.google.com/maps/api/geocode/json?address=".urlencode($address);

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
 $responseJson = curl_exec($ch);
 curl_close($ch);

 $response = json_decode($responseJson);
 
 $ad = [];

 if ($response->status == 'OK') {
  
  $ad['geolocation_lat'] = $response->results[0]->geometry->location->lat;
  $ad['geolocation_long'] = $response->results[0]->geometry->location->lng;
  $result = $response->results[0];
  //get state and country
  
   foreach($result->address_components as $address_component)
   {
    
    
    //console.log(obj);
    if(in_array('country',$address_component->types))
    { 
     $ad['geolocation_country_short']=$address_component->short_name;
     $ad['geolocation_country_long']=$address_component->long_name;
     
    }else if(in_array("administrative_area_level_1",$address_component->types))
    { 
     $ad['geolocation_state_short']=$address_component->short_name;
     $ad['geolocation_state_long']=$address_component->long_name;
    }
    
    
   }
  
  //get state and country
  $ad['formatted_address']=$result->formatted_address;
 }
 return $ad;
}
$geo=getting_address('Tennesee,USA');
echo '<pre>';
print_r($geo);

OUTPUT

Array
(
    [geolocation_lat] => 16.9316721
    [geolocation_long] => 82.088374
    [geolocation_state_short] => AP
    [geolocation_state_long] => Andhra Pradesh
    [geolocation_country_short] => IN
    [geolocation_country_long] => India
    [formatted_address] => Gandredu, Andhra Pradesh 533344, India
)

No comments:

Powered by Blogger.