How To Get Address From Latitude And Longitude Google Map Api


In this tutorial, you learn how to get address from latitude and longitude google map API in Codeigniter.

For many projects, we need to get latitude and longitude from addresses in PHP Codeigniter. Google has provided an API name google maps geocoding API. In this tutorial, we will use this API and get google maps geocoder get latitude and longitude. 

How To Get Address From Latitude And Longitude Google Map Api


How To Get Latitude and Longitude From Address in Codeigniter Using google map API.

Follow the below steps and get the address from latitude and longitude google map API in PHP Codeigniter:

Use Google API With Key Example
https://maps.google.com/maps/api/geocode/json?address='.$address.'&key=your_api_key
2. Create Functions To Getting Address

We need to create two functions in the first is getlocation() and second one is get_longitude_latitude_from_adress(). Use these functions and get google maps geocoder get latitude and longitude using Codeigniter.

Explanation of created functions to get latitude and longitude in google maps geocoding API

getlocation():- When we pass the address in this function, inside this function we will call the get_longitude_latitude_from_adress() this function with address and it will return latitude and longitude from the address in Codeigniter using google maps geocoding API.

get_longitude_latitude_from_adress():- In this function, we will pass the address and this function call google geocode APIs and get address from latitude and longitude google map api.

public function getlocation()
{
    $address = "United States of America";
    $array  = $this->get_longitude_latitude_from_adress($address);
    $latitude  = round($array['lat'], 6);
    $longitude = round($array['long'], 6);           
}
 
function get_longitude_latitude_from_adress($address){
  
$lat =  0;
$long = 0;
 
 $address = str_replace(',,', ',', $address);
 $address = str_replace(', ,', ',', $address);
 
 $address = str_replace(" ", "+", $address);
  try {
 $json = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$address.'&key=your_api_key');
 $json1 = json_decode($json);
 
 if($json1->{'status'} == 'ZERO_RESULTS') {
 return [
     'lat' => 0,
     'lng' => 0
    ];
 }
 
 if(isset($json1->results)){
    
    $lat = ($json1->{'results'}[0]->{'geometry'}->{'location'}->{'lat'});
    $long = ($json1->{'results'}[0]->{'geometry'}->{'location'}->{'lng'});
  }
  } catch(exception $e) { }
 return [
 'lat' => $lat,
 'lng' => $long
 ];
}

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close