Codeigniter 4 Autocomplete Address using Google API Example

In this tutorial, we will show you how to implement autocomplete address using Google API in Codeigniter 4.

Google Maps API provides a great way to show location-based data on a map. It also provides an autocomplete feature which helps users to quickly select an address from the list.

In this tutorial, we will use Google Maps API to implement autocomplete address in Codeigniter 4.

Step 1 – Create a Codeigniter 4 Project

First of all, we need to create a Codeigniter 4 project. So, open the terminal and execute the following command to create a Codeigniter 4 project.

composer create-project codeigniter4/appstarter codeigniter-google-autocomplete

Step 2 – Setup Database Credentials

After creating the project, we need to setup the database credentials. So, open the .env file and add the database credentials in it.

database.default.hostname = localhost database.default.database = ci4 database.default.username = root database.default.password = root database.default.DBDriver = MySQLi

Step 3 – Create a Table

In this step, we will create a table in the database. So, open the phpMyAdmin and create a table with the following SQL query.

CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(100) NOT NULL, `address` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 4 – Create a Model

In this step, we will create a model. So, create a model file UserModel.php in the app/Models directory and add the following code in it.

$this->request->getPost(‘name’), ‘address’ => $this->request->getPost(‘address’) ]; $model->save($data); return redirect()->to(‘/’); } }

Step 6 – Create a View

In this step, we will create a view file. So, create a view file index.php in the app/Views/user directory and add the following code in it.

<?php echo $title; ?>

Codeigniter 4 Autocomplete Address using Google API

Step 7 – Run the Application

In this step, we will run the application. So, open the terminal and execute the following command to run the application.

php spark serve

Now, open the browser and hit the following URL.

http://localhost:8080

Conclusion

In this tutorial, we have learned how to implement autocomplete address using Google API in Codeigniter 4.
[ad_1]

Google autocomplete place/address in codeigniter 4 apps. In this tutorial, you will learn how to implement autocomplete address search bar app with codeigniter 4 and google api.

And this tutorial will guide you step by step on how to create Google autocomplete place/address without showing the google map in Codeigniter 4 app.

First of all, You need to get API key before you can make calls to the Google Maps Geocoding service.

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 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.)

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

By using the following steps, you can add google autocomplete address or places functionality in Codeigniter 4 apps:

  • Step 1: Setup Codeigniter 4 Project
  • Step 2: Basic Configurations
  • Step 3: Setup Database Credentials
  • Step 4: Create a Controller
  • Step 5: Create a View
  • Step 6: Define Routes
  • Step 7: Start Development Server

Step 1: Setup Codeigniter 4 Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

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

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

	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 a Controller

In this step, Visit app/Controllers and create a controller name GoogleAutocompleteAddress.php. In this controller, you need to add the following methods into 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 a View

In this step, you need to create one view files name home.php and update the following code into your file:

<!doctype html>
<html lang="en">
<head>
<title>Codeigniter 4 Google Autocomplete Address Example</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" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></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" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></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

Finally, need to implement javascript code for implement google autocomplete search address with api. Now you need to add following code on script tag after the closing of body tag on 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 – Define Routes

In this step, you need to create a route that renders the table into the view, place the following code in app/Config/Routes.php file.

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

Step 7 – Start Development Server

In this step, open your terminal and execute the following command to start development sever:

php spark serve

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

http://localhost:8080

Conclusion

Codeigniter 4 google autocomplete address example. In this tutorial, you have learned how to autocomplete address in codeigniter 4 app using google api

Recommende CodeIgniter 4 Tutorial

If you have any questions or thoughts to share, use the comment form below to reach us.

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00