Codeigniter 4 Draw Multiple Markers On Google Map Tutorial Example

Codeigniter 4 , Codeigniter

Nicesnippets

341

21-08-2021


Codeigniter 4 Draw Multiple Markers On Google Map Tutorial Example

Hi guys,

Today i will explained Draw Multiple Markers On Google Map in Codeigniter 4. This example is so easy to use in Codeigniter 4.

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.

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.

So let's start to the example.

Step 1: Create Codeigniter Project


Codeigniter Project Project install in a two ways.

composer create-project codeigniter4/appstarter

Step 2: CI Error Handling

This step is completely optional, if you want you can open app/Config/Boot/production.php and set display_errors property to 1 and enable the error debugging in Codeigniter app.

ini_set('display_errors', '1');

Step 3: 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.

Step 4: Connect To Database

Open the app/Config/Database.php, and insert database name, username and password into the 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',

]

Step 5: Create Table With 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');

Step 6: Formulate Controller

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

app/Controllers/GMapController.php

<?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);

}

}

Step 7: Create Route

app/Config/Routes.php

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

Step 8: Set Up Map View

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">

<meta name="description" content="The tiny framework with powerful features">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Codeigniter 4 Draw Multiple Markers On Google Map Tutorial Example - Nicesnippets.com</title>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/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>

</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>

</body>

</html>

Step 9: Run CI Application

In this last step, you have to open the terminal, type command to run the application.

php spark serve

Then next run the url in your browser.

http://localhost:8080/

Output

Now you can check your own.

I hope it can help you...


Recommended Posts