Codeigniter 4 Google Autocomplete Address Search Box Tutorial

Last updated on: by Digamber

Google autocomplete search box displays the places, address and location as soon as the user starts typing in the form input widget; it provides address suggestion within a fraction of seconds.

Cool, isn’t it? What if you have to implement the same feature in your app.

Fret not! We will help you; through this profound step-by-step guide, we will teach you how to add google autocomplete address/place the search box in Codeigniter 4 app using the Google API.

Google API allows you to access location data; to acquire the google API you need to visit the google cloud platform. In addition to that, we will suggest how to eloquently grab the API from the Google cloud platform and display the auto-suggest addresses and places in the Codeigniter application.

How to Add Autocomplete Address Search in Codeigniter 4 using Google API

  • Step 1: Create Codeigniter Project
  • Step 2: CI Error Handling
  • Step 3: Get Google Maps API Key
  • Step 4: Connect to Database
  • Step 6: Create Controller
  • Step 7: Create Route
  • Step 8: Add Autocomplete Widget in View
  • Step 9: Run CI Application

Create Codeigniter Project

Let us install the Codeigniter app through composer, and I assume you have set up the tool in advance.

composer create-project codeigniter4/appstarter

Another way is to download the Codeigniter app from their site. Make sure to unzip and rename the project after you dowloaded and installed.

CI Error Handling

For error debugging, change display_errors prop’s value to 1 in app/Config/Boot/production.php.

ini_set('display_errors', '1');

Get Google Maps API Key

Our next task is to get Google API key, it will enable the communication between client and Google server. Here are the instructions going towards grabbing the Google API.

  • Visit Google Cloud Platform.
  • Next, click on the project dropdown at the top to create the project.
  • Click APIs & Services > Credentials.
  • Next, click on Create Credentials > API key.
  • Copy google API and store in some text file.
  • Next, enable few services, so click on Credentials > “Enable APIs and Services”, additionally enable “Maps JavaScript API” and “Places API” services.

Connect to Database

Next, insert database name, username and password values in the app/Config/Database.php file.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Setting Up Controller

Controller does plenty of work, however at the moment we need it to load the view template, so create controller file (AutocompleteController.php) in Controllers directory, after which open and update the given below code in app/Controllers/AutocompleteController.php.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;

class AutocompleteController extends Controller
{

  public function index() {
    return view('index');
  }

}

Create Route

Next, add the new route for displaying the Google autocomplete address search box component in the Codeigniter application, therefore update the app/Config/Routes.php.

$routes->get('/', 'AutocompleteController::index');

Implement Google Autocomplete Search in Codeigniter

To view the autocomplete location search, create the view file, it allows us to integrate Google autocomplete search box in Codeigniter.

Create the index.php view file in app/Views/, then update the app/Views/index.php with given code.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Codeigniter Google Autocomplete Address Search Example</title>
	<meta name="description" content="The tiny framework with powerful features">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
	<style>
	  .container {
		max-width: 500px;
	  }
	</style>
</head>
<body>

<div class="container mt-4">

<div class="form-group mb-3">
   <h3 class="mb-3"> Find Address or Location</h3>
   <input type="text" name="autocomplete" id="autocomplete" class="form-control" placeholder="Choose Location">
</div>

<div class="form-group mb-3" id="latitudeArea">
   <label>Latitude</label>
   <input type="text" class="form-control" name="latitude" id="latitude">
</div>

<div class="form-group mb-3" id="longtitudeArea">
   <label>Longitude</label>
   <input type="text" class="form-control" name="longitude" id="longitude">
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCMwpWumynr-7cPLX_paKYViBYFqqnUidc&libraries=places&callback=initAutocomplete"></script>

<script>
    $(document).ready(function() {
        $("#latitudeArea").addClass("d-none");
        $("#longtitudeArea").addClass("d-none");
    }); 
	
    google.maps.event.addDomListener(window, 'load', initialize);

	function initialize() {
		var input = document.getElementById('autocomplete');
		var autocomplete = new google.maps.places.Autocomplete(input);
		
		autocomplete.addListener('place_changed', function() {
			var place = autocomplete.getPlace();
			
			$('#latitude').val(place.geometry['location'].lat());
			$('#longitude').val(place.geometry['location'].lng());
			
			$("#latitudeArea").removeClass("d-none");
			$("#longtitudeArea").removeClass("d-none");
		});
	} 
</script>

</div>


</body>
</html>

Run CI Application

Now, start the Codeigniter project, moreover execute the given url on the browser to view the app in the browser.

php spark serve
http://localhost:8080

Google Autocomplete Address Search in Codeigniter

Conclusion

We have explained about adding Autocomplete search address form in CodeIgniter using Google map API key. We went through all over from begging.

Not just we taught you how to implement Autocomplete places search box, but we also explained how to get google API from scratch.

So, eventually, this Codeigniter 4 Google address autocomplete tutorial is completed.

Digamber

I am Digamber, a full-stack developer and fitness enthusiast. I crafted this site to bestow my coding experience and love to write on JavaScript, React, Angular, Vue, Laravel.