CodeIgniter 4 Autocomplete Places Search Box Using Google Maps JavaScript API

Reading Time: 6 minutes
1,071 Views

Inside this article we will see the concept i.e CodeIgniter 4 Autocomplete Places Search Box using Google Maps JavaScript API Tutorial. Article contains the classified information about google places autocomplete search box using google map api and JavaScript.

If you are looking for a solution i.e how to use google place api to create autocomplete search box for places in CodeIgniter then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.

Note that, Google autocomplete address API will return address and as well as latitude, longitude, place code, state, city, country, etc. Using latitude and longitude of address, you can show markers location in google map dynamically.

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Getting Started with Google Map API Key

Before using the Places library in the Maps JavaScript API, first you need to make sure that the Places API is enabled in the Google Cloud Console, in the same project you set up for the Maps JavaScript API.

To view your list of enabled APIs:

  • Go to the Google Cloud Console.
  • Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open.
  • From the list of APIs on the Dashboard, look for Places API.
  • If you see the API in the list, you’re all set. If the API is not listed, enable it:
    1. At the top of the page, select ENABLE API to display the Library tab. Alternatively, from the left side menu, select Library.
    2. Search for Places API, then select it from the results list.
    3. Select ENABLE. When the process finishes, Places API appears in the list of APIs on the Dashboard.

Map API Key will look like this:

AIzaxxxXSQRl-XLDybXXX9cBcNtoZ1HXXxXxxXX

Assuming you have your correct Map API Key.

Create Controller

Open project into terminal and run this command to create controller file.

$ php spark make:controller PlaceController

It will create a file PlaceController.php inside /app/Controllers folder.

Open this controller file and write this code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class PlaceController extends BaseController
{
	public function index()
	{
		return view("autocomplete-places");
	}
}

Create View Template

Next,

Create a file autocomplete-places.php inside /app/Views folder. Open view file and write this code into it.

<!doctype html>
<html lang="en">

<head>
    <title>CodeIgniter 4 Autocomplete Places Search Box using Google Maps JavaScript API</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-10 col-lg-10 col-md-10 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 Autocomplete Places Search Box using Google Maps JavaScript API</h5>
                    </div>

                    <div class="card-body">
                        <div class="form-group">
                            <label for="autocomplete"> Location </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://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://maps.google.com/maps/api/js?key=AIzaxxxXSQRl-XLDybXXX9cBcNtoZ1HXXxXxxXX&libraries=places&callback=initAutocomplete" type="text/javascript"></script>
    <script src="<?php echo base_url('map.js') ?>"></script>
</body>

</html>
                              

When page loads, initAutocomplete() will be called.

<script src="https://maps.google.com/maps/api/js?key=AIzaxxxXSQRl-XLDybXXX9cBcNtoZ1HXXxXxxXX&libraries=places&callback=initAutocomplete" type="text/javascript"></script>

Create ‘map.js’ File

Create a file map.js inside /public folder. Inside this file we will write code for map settings.

Open map.js file and write this code into it.

//...

$(document).ready(function() {
    $("#lat_area").addClass("d-none");
    $("#long_area").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());

        // --------- show lat and long ---------------
        $("#lat_area").removeClass("d-none");
        $("#long_area").removeClass("d-none");
    });
}

//...

Add Route

Open Routes.php from /app/Config folder. Add this route into it.

//...

$routes->get("locations", "PlaceController::index");

//...

Application Testing

Open project terminal and start development server via command:

$ php spark serve

URL: http://localhost:8080/locations

Whenever you search and click on any location, you will get latitude and longitude of selected location.

We hope this article helped you to learn CodeIgniter 4 Autocomplete Places Search Box using Google Maps JavaScript API in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.