PHP Codeigniter 4 Get Latitude / Longitude from Address Example

Codeigniter 4 Get Latitude and Longitude from Address tutorial; This tutorial will help you discover how to systematically and programmatically get latitude and longitude from the address in Codeigniter 4 application using the Google API keys.

In application development, you seldom require to work with maps, locations etc.

What if you have to retrieve latitude and longitude from an address in Codeigniter. Well, today, we have brought you the ready-made solution for dealing with such kind of functionality.

Before we begin, we would like to tell you we will need a Codeigniter application, a controller most importantly, Google Geocode API keys to fetch the lat and long from an address in the PHP Codeigniter application.

Get the Google API key.

In order to make a request to Google Maps Geocoding, you need to have Google API.

If you wonder how to get the work done, don’t worry; the following steps guide you to acquire the keys in no time.

Before you start consuming the Maps Static API, you must have a project with a billing account, and the Maps Static API enabled. 

To learn more, please check Set up in Cloud Console.

You must have at least one API key associated with your project.

  1. Head over to Google Cloud Console.
  2. Click the project dropdown and choose or create the project for which you want to add an API key.
  3. Click the menu button and select Google Maps Platform > Credentials.
  4. On the Credentials page, click + Create Credentials > API key.
  5. The API key created dialog displays the newly created API key.
  6. Click Close.
  7. The new API key is listed on the Credentials page under API Keys.

How to Restrict the API key

It is essential to restrict the API key before you try your hands-on production; here is the proper assortment of instructions.

If you allow only authorized requests to be triggered from your API, append one more layer of security to your app.

Here are the steps involving setting the restriction on your API keys.

  1. Go to the Google Maps Platform > Credentials page.
  2. Go to the Credentials page
  3. Select the API key that you want to set a restriction on. The API key property page appears.
  4. Under Key restrictions, set the following restrictions:
    • Application restrictions:
      1. To accept requests from the list of websites that you supply, select HTTP referrers (web sites) from the list of Application restrictions.
  1. Specify one or more referrer web sites. For example, *.google.com accepts all sites ending in google.com, such as https://developers.google.com.
      1. Note: file:// referers need a special representation to be added to the key restriction. The “file://” part should be replaced with “__file_url__” before being added to the key restriction. For example, “file:///path/to/” should be formatted as “__file_url__//path/to/*”. After enabling file:// referers, it is recommended you regularly check your usage, to make sure it matches your expectations.
    • API restrictions:
      1. Click Restrict Key.
      2. Select Maps Static API from Select APIs dropdown. If the Maps Static API is not listed, you need to enable it.
  1. To finalize your changes, click Save.

 

How to Find Out Latitude and Longitude from Address in PHP Codeigniter 4

You need to set up a controller in order to fetch the lat and long, define a single class, and getLatLong() and grabLatLongFromAddress() functions.

The getLatLong() is the primary function which initializes the grabLatLongFromAddress() function.

As you can recognize, you need to pass the address dynamically to the grabLatLongFromAddress($address) function; It will render lat and long from address using the google geocode API profoundly.

<?php

namespace App\Controllers;
use CodeIgniter\Controller;


class LocationFinderController extends Controller {

    public function getLatLong()
    {
        $address = "Sarangani Philippines";
        $array  = $this->grabLatLongFromAddress($address);
        $latitude  = round($array['lat'], 6);
        $longitude = round($array['long'], 6);           
    }
     
    function grabLatLongFromAddress($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.'&amp;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
        ];
    }

} ?>

These functions can also be get aligned with helper functions and might be relentlessly used to obtain latitude and longitude from address.

Summary

In laymen’s terms, Latitude and longitude are lines utilized to define the location of any place on Earth where lines of Latitude run in an east-west direction across Earth and longitude line run in a north-south direction.

In this Codeigniter get Latitude and longitude from address tutorial, we described how to build such functionality which returns the lat and long based on address.