Get Latitude And Longitude From Address Tutorial Using Codeigniter 4 Example


Share:
Published By: Admin, Published On: Sep 08, 2021, Category: Codeigniter 4 Codeigniter


Hello Friends,

Now let's see example of how to get latitude and longitude from address in codeigniter 4. We will use how to use to get latitude and longitude from address using in codeigniter 4. Here you will learn how to use to get latitude and longitude from address in codeigniter 4. We will use to get latitude and longitude from address using codeigniter. Let's get started with how to to get latitude and longitude from address use in codeigniter 4.

Here i will give you many example how you can use to get latitude and longitude from address in codeigniter 4.

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
];

It will help you....

Share: