Codeigniter 4 Autocomplete Address using Google API Example

In this tutorial, you’ll learn how to make a search bar app that autocompletes addresses using CodeIgniter 4 and Google API. You don’t need to show a map to use this feature.

To get started, you’ll need an API key. This will allow you to make calls to the Google Maps Geocoding service. The tutorial will guide you through each step.

First, you will have to visit: https://cloud.google.com/maps-platform/?_ga=2.27293823.277869946.1577356888-568469380.1576660626#get-started and get the API key.

Steps of to get an API key From Google Console:

  1. Visit the Google Cloud Platform Console.
  2. Click the project drop-down and select or create the project for which you want to add an API key.
  3. Click the menu button  and select APIs & Services > Credentials.
  4. On the Credentials page, click Create credentials > API key.
    The API key created dialog displays your newly created API key.
  5. Click Close.
    The new API key is listed on the Credentials page under API keys.
    (Remember to restrict the API key before using it in production.)

Autocomplete Address Google Api with PHP Codeigniter 4

  • Download Codeigniter 4 Project
  • Basic Configurations
  • Setup Database Credentials
  • Create Controller
  • Create View
  • Create Route
  • Start Development Server

Step 1 – Download Codeigniter 4 Project

Let’s begin by downloading the latest version of CodeIgniter 4 from the official website. You can download it from this link: https://codeigniter.com/download. Once downloaded, extract the files and save them in your local system’s xampp/htdocs/ directory.

Now, change the folder name to “demo” to make it easy to remember and work with. This step is important as we will be using the CodeIgniter 4 framework for our image file upload example.

Step 2 – Basic Configurations

Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Setup Database Credentials

Now, we have to link our project to the database. To do this, go to app/Config/Database.php and open the database.php file in a text editor. Once you have opened the file, you need to enter your database details in the file just like this:

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

Step 4 – Create Controller

Next, we will create a controller named GoogleAutocompleteAddress.php. To do this, go to app/Controllers and create a new file with this name. Once you have created the file, you need to add the following methods to it:

<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
 
 
class GoogleAutocompleteAddress extends Controller
{
 
    public function index() {
      return view('home');
    }
 
}

Step 5 – Create View

Now, we will create a view file named home.php. To do this, you need to create a new file with this name. Once you have created the file, you need to update the code in the file with the following:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Codeigniter 4 Google Autocomplete Address Example - torqueprogramming.co.in</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
        <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
    </head>
    <body>
        <div class="container mt-5">
            <div class="row">
                <div class="col-xl-6 col-lg-6 col-md-8 col-sm-12 col-12 m-auto">
                    <div class="card shadow">
                        <div class="card-header bg-primary">
                            <h5 class="card-title text-white">Codeigniter 4 Google Autocomplete Address</h5>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="autocomplete"> Location/City/Address </label>
                                <input type="text" name="autocomplete" id="autocomplete" class="form-control" placeholder="Select Location" />
                            </div>
                            <div class="form-group" id="lat_area">
                                <label for="latitude"> Latitude </label>
                                <input type="text" name="latitude" id="latitude" class="form-control" />
                            </div>
                            <div class="form-group" id="long_area">
                                <label for="latitude"> Longitude </label>
                                <input type="text" name="longitude" id="longitude" class="form-control" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    </body>
    <script src="https://maps.google.com/maps/api/js?key=AIzaSyDxTV3a6oL6vAaRookXxpiJhynuUpSccjY&libraries=places&callback=initAutocomplete" type="text/javascript"></script>
    <script>
        $(document).ready(function () {
            $("#lat_area").addClass("d-none");
            $("#long_area").addClass("d-none");
        });
    </script>
    <script>
        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());
                // --------- show lat and long ---------------
                $("#lat_area").removeClass("d-none");
                $("#long_area").removeClass("d-none");
            });
        }
    </script>
</html>

Implement Javascript code

Lastly, we will implement the JavaScript code for the Google Autocomplete search address using an API. To do this, you need to add the following code to a script tag after the closing of the body tag in the view file:

<script src="https://maps.google.com/maps/api/js?key=AIzaSyDxTV3a6oL6vAaRookXxpiJhynuUpSccjY&libraries=places&callback=initAutocomplete" type="text/javascript"></script>
<script>
    $(document).ready(function () {
        $("#lat_area").addClass("d-none");
        $("#long_area").addClass("d-none");
    });
</script>
<script>
    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());
            // --------- show lat and long ---------------
            $("#lat_area").removeClass("d-none");
            $("#long_area").removeClass("d-none");
        });
    }
</script>

Step 6 – Create Route

Now, we will create a route that displays the table in the view. To do this, you need to add the following code to the app/Config/Routes.php file:

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

Step 7 – Start Development Server

Next, open your terminal and run the following command to start the development server:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080

You May Also Like

  1. CodeIgniter 4 Server Side DataTable Example
  2. Codeigniter 4 Google Map Multiple Markers Example
  3. Codeigniter 4 Get Latitude and Longitude From Address
  4. Country State City Dependent Dropdown in Codeigniter 4
  5. Codeigniter 4 Import Data to Excel/CSV File From MySQL Database
  6. Codeigniter 4 Dynamic Dependent Dropdown with Ajax
  7. Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS
  8. Codeigniter 4 PDF Generator Tutorial Example
  9. Crop and Save Image using jQuery Coppie in Codeigniter 4

Leave a Reply

Your email address will not be published. Required fields are marked *