Codeigniter 4 Draw Multiple Markers on Google Map Tutorial

Last updated on: by Editorial Team

This extensive guide will show you how to draw multiple location markers on Google map in Codeigniter 4 application using the Google map API key.

Identifying a place in a map becomes easy with location makers; we will help you understand the nuances required to show multiple markers on Google Maps from the database in the CodeIgniter app. After you finish this tutorial, you will understand how to display Google Maps using latitude and longitude in the PHP Codeigniter application.

A marker is an icon or image added on the Google map; it helps locate a particular location on the map. By default, the marker is an icon pointing towards your location. However, you can replace a marker image with a custom image or icon. Similarly,

We will begin with the basic app installation process, connect with the database, and obtain the Google Maps API key from the google cloud platform dashboard. Furthermore, we will explain how to integrate markers (location) in Google Maps in conjunction with our CodeIgniter app.

Let us start Google Maps integration in the Codeigniter app from absolute scratch.

How to Add Multiple Markers in Google Maps Codeigniter 4

  • Step 1: Create Codeigniter Project
  • Step 2: CI Error Handling
  • Step 3: Get Google Maps API Key
  • Step 4: Connect to Database
  • Step 5: Create Table with Location Data
  • Step 6: Formulate Controller
  • Step 7: Create Route
  • Step 8: Set Up Map View
  • Step 9: Run CI Application

Create Codeigniter Project

Codeigniter app can be downloaded through two methods, Composer CLI and direct download.

Execute below command from the command line tool, make sure you have already set up composer.

composer create-project codeigniter4/appstarter

Second method is the direct method, so download the Codeigniter app straight from the official site.

Next, unzip and rename the project name as per your choice.

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

Google Maps API key helps communicate with the maps; we have mentioned the simple process to obtain the map API below.

  • Go to Google Cloud Platform.
  • Now, create the project, click on the project dropdown at the top left section.
  • Head over to APIs & Services > Credentials.
  • Click on Create Credentials > API key.
  • After clicking on Api key, a model appears with map API key, copy for later use and keep it in the text file.
  • Click on Credentials > “Enable APIs and Services”, also 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,
    ];

To fix the “Unable to connect database: Codeigniter error”, change the hostname value in your database’s default array pass the localhost server value based on the localhost server you are using.

# MAMP
public $default = [

  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
]

# XAMP
public $default = [
  
  'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

]

Create Table with Location Data

To show or display multi-location pins on the Google map, we need location data. Hence we decided to do it quickly using the SQL query.

Execute the following SQL query to create the user_locations table in the database and add some random location data.

CREATE TABLE user_locations (
   id int(11) NOT NULL AUTO_INCREMENT,
   latitude varchar(20) COLLATE utf8_unicode_ci NOT NULL,
   longitude varchar(20) COLLATE utf8_unicode_ci NOT NULL,
   location_name varchar(100) COLLATE utf8_unicode_ci NOT NULL,
   info varchar(255) COLLATE utf8_unicode_ci NOT NULL,
   PRIMARY KEY (id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 INSERT INTO user_locations (id, latitude, longitude, location_name, info) VALUES
   (1, '36.778259', '-119.417931', 'California', 'Sacramento, USA'),
   (2, '31.968599', '-99.901810', 'Texas', 'Austin, USA'),
   (3, '27.664827', '-81.515755', 'Florida', 'Tallahassee, USA'),
   (4, '41.6809707', '44.0287382', 'Georgia', 'Atlanta, USA'),
   (5, '38.8950368', '-77.0365427', 'Washington', 'Olympia, USA');

Formulate Controller

Now, we have to formulate a new controller; in this single class, we will define a function, it gets the location data from the database and shows multiple location pins or markers on the map.

Create controller file (GMapController.php) in Controllers folder, then open and add following code in app/Controllers/GMapController.php file.

<?php 

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


class GMapController extends Controller
{

    public function showMap() {
         
        $database      = \Config\Database::connect();
        $queryBuilder = $database->table('user_locations');  
 
        $query = $queryBuilder->select('*')->limit(30)->get();
        $records = $query->getResult();
 
        $locationMarkers = [];
        $locInfo = [];
 
        foreach($records as $value) {
          $locationMarkers[] = [
            $value->location_name, $value->latitude, $value->longitude
          ];          
          $locInfo[] = [
           "<div class=info_content><h4>".$value->location_name."</h4><p>".$value->info."</p></div>"
          ];
        }
        $location['locationMarkers'] = json_encode($locationMarkers);
        $location['locInfo'] = json_encode($locInfo);
     
        return view('index', $location);
    }

}

Create Route

In the subsequent step, you have to register the new route for displaying the Google Map in the Codeigniter app, hence place the code in app/Config/Routes.php file.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->get('/', 'GMapController::showMap');

Add Multiple Markers in Google Map

In this section, you will see how to add multiple Markers in Google Map and show the location markers on google map.

Use the Google map API key in the maps script; we obtained map API earlier from the google cloud console.

Thus, create the index.php, file in app/Views/ folder, after that add the provided code in app/Views/index.php file.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Codeigniter 4 Show Multiple Markers on Google Map 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: 1000px;
	  }
	  #gmapBlock {
		  width: 100%;
		  height: 450px;
	  }
	</style>
</head>
<body>

<div class="container mt-5">

<div id="gmapBlock"></div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
	$(function() {
			var script = document.createElement('script');
				script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
				document.body.appendChild(script);
			});
			
			function initialize() {
			var map;
			var bounds = new google.maps.LatLngBounds();
			var mapOptions = {
				mapTypeId: 'roadmap'
			};
							
			map = new google.maps.Map(document.getElementById("gmapBlock"), mapOptions);
			map.setTilt(45);
			
			var locationMarkers = JSON.parse(`<?php echo ($locationMarkers); ?>`);
			
			var locInfo = JSON.parse(`<?php echo ($locInfo); ?>`);       
				
			var infoWindow = new google.maps.InfoWindow(), marker, i;
			
			for( i = 0; i < locationMarkers.length; i++ ) {
				var position = new google.maps.LatLng(locationMarkers[i][1], locationMarkers[i][2]);
				bounds.extend(position);
				marker = new google.maps.Marker({
					position: position,
					map: map,
					title: locationMarkers[i][0]
				});
				
				google.maps.event.addListener(marker, 'click', (function(marker, i) {
					return function() {
						infoWindow.setContent(locInfo[i][0]);
						infoWindow.open(map, marker);
					}
				})(marker, i));
			
				map.fitBounds(bounds);
			}
			
			var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
				this.setZoom(5);
				google.maps.event.removeListener(boundsListener);
			});
	
	}
</script>
</div>


</body>
</html>

Run CI Application

In this step, you have to run the Codeigniter application using the below command, additionally use the provided url to start the app in the browser.

php spark serve
http://localhost:8080

Draw Multi Markers and Pins on Google Map in Codeigniter

Conclusion

In this comprehensive guide, you understood the nuance of Google map integration in Codeigniter eloquently. We specifically share how to add or show multiple markers on Google Maps using google API in PHP Codeigniter app.