CodeIgniter 4 Get Latitude / Longitude From Address Tutorial

Last Updated on by in CodeIgniter

How to get latitude and longitude from an address in PHP Codeigniter 4? well, we have a custom solution for you; in this tutorial, you will find out the simple way to get latitude and longitude from an address in Codeigniter using the Google API.

However, we will not take the help of Google Map.

Codeigniter 4 Get Latitude and Longitude From Address Example

Before you start creating the CI project, you need to create Google Maps API for getting address from latitude and longitude.

The getlocation() method helps to invoke the getAddress() function; consequently, it returns the address based on latitude and longitude.

Similarly, the getAddress() method gets address based on lat and long using the Google Maps API.

public function getlocation()
{
    $address = "Chennai India";
    $array  = $this->getAddress($address);
    $latitude  = round($array['lat'], 6);
    $longitude = round($array['long'], 6);           
}
 
function getAddress($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 [
            'latitude' => 0,
            'longitude' => 0
            ];
        }
 
 if(isset($json1->results)){
    
    $lat = ($json1->{'results'}[0]->{'geometry'}->{'location'}->{'latitude'});
    $long = ($json1->{'results'}[0]->{'geometry'}->{'location'}->{'longitude'});
  }
  } catch(exception $e) { }
    return [
    'latitude' => $latitude,
    'longitude' => $longitude
    ];
}

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.