Codeigniter 4 Google Map Multiple Markers Example - Yudhy Network

Share on:

Yudhy Network - Codeigniter 4 display multiple markers on google map. In this tutorial, you will learn how to show multiple locations on google map in codeigniter 4

Codeigniter 4 show/add multiple markers on google map tutorial. This tutorial would love to share with you how to add multiple markers on google map from database php codeigniter Using javascript. And will also add/show multiple infowindows with multiple markers using javascript.

Sometime you need to show/add multiple markers with infowindows(like users name, user contact detail, user other info) on google map from database php codeigniter. So,You will learn each thing step by step about multiple markers and multiple infowindows on google map.

How to add multiple map marker points in your embedded google map, instead of embedded google map, In this tutorial, you will learn from scratch on how to add or display multiple markers on google map using api in PHP Codeigniter 4 app.

How to add multiple markers in google map in Codeigniter 4 app

  • Download Codeigniter 4 Project
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Controller
  • Create View
  • Start Development server
  • Conclusion

Step 1: Download 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/';
Recommended:- CodeIgniter 4 jQuery Form Validation Example

Step 3 – Create Table in Database

In this step, you need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo . After successfully create a database, you can use the below sql query for creating a table in your database. you will add some cities with city info.

CREATE TABLE 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,
   location_info varchar(255) COLLATE utf8_unicode_ci NOT NULL,
   PRIMARY KEY (id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 INSERT INTO locations (id, name, email, contact_no, created_at) VALUES
   (1, '24.794500', '73.055000', 'Pindwara', 'Pindwara, Rajasthan, India'),
   (2, '21.250000', '81.629997', 'Raipur', 'Chhattisgarh, India'),
   (3, '16.166700', '74.833298', 'Gokak', 'Gokak, Karnataka, India'),
   (4, '26.850000', '80.949997', 'Lucknow', 'Lucknow, Uttar Pradesh, India'),
   (5, '28.610001', '77.230003', 'Delhi', 'Delhi, the National Capital Territory of Delhi, India'),
   (6, '19.076090', '72.877426', 'Mumbai', 'Mumbai, Maharashtra, The film city of India'),
   (7, '14.167040', '75.040298', 'Sagar', 'Sagar, Karnataka, India'),
   (8, '26.540457', '88.719391', 'Jalpaiguri', 'Jalpaiguri, West Bengal, India'),
   (9, '24.633568', '87.849251', 'Pakur', 'Pakur, Jharkhand, India'),
   (10, '22.728392', '71.637077', 'Surendranagar', 'Surendranagar, Gujarat, India'),
   (11, '9.383452', '76.574059', 'Thiruvalla', 'Thiruvalla, Kerala, India');

Step 4 – 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,
	];
Recommended:- CodeIgniter 4 Ajax Form Submit Validation Example

Step 5 – Create Controller

In this step, you need to create a controller name GoogleMap.php. In this controller you will create some method/function. And build some of the methods like :

  • Index() – This is used to showing cities markers with infowindow on google map
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;


class GoogleMap extends Controller
{

       public function index() {
        
        $db      = \Config\Database::connect();
        $builder = $db->table('locations');  

        $query = $builder->select('*')->limit(20)->get();
        $data = $query->getResult();

        $markers = [];
        $infowindow = [];

        foreach($data as $value) {
          $markers[] = [
            $value->location_name, $value->latitude, $value->longitude
          ];          
          $infowindow[] = [
           "<div class=info_content><h3>".$value->location_name."</h3><p>".$value->location_info."</p></div>"
          ];
        }
        $location['markers'] = json_encode($markers);
        $location['infowindow'] = json_encode($infowindow);
    
        return view('map_marker',$location);
    }

}

In this controller function, you fatch the record from database and created markers, infowindows in this google.php controller. After you have created markers and infowindows, pass this data to views.

Step 6 – Create View

Now you need to create map_marker.php, go to application/views/ folder and create map_marker.php file. Here put the below html code for showing list of product.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Google Maps Multiple Marker(Pins) In Codeigniter 4 - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>

<div class="container">
  <div class="row">
  <div class="col-12">
   <div class="alert alert-success"><h2>Codeigniter 4 Display Multiple Markers on Google Maps - Tutsmake.com</h2>
   </div>
   <div id="map_wrapper_div">
    <div id="map_tuts"></div>
   </div>
  </div>
</div>
</body>
</html>

Includes Api Key

Load the Google Map JavaScript API and specify an API key in the key parameter and include on map_marker .php file

<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY"></script>
Recommended:- CodeIgniter 4 Image Upload With Preview Example

Implement css

In this step you will implement some css for google map styling. Now put the css code on head section :

<style>
.container{
  padding: 2%;
  text-align: center;

 } 
 #map_wrapper_div {
  height: 400px;
}

#map_tuts {
    width: 100%;
    height: 100%;
}
</style>

Implement Javascript code

Finally you will implement javascript code for creating a map on web pages and adding and showing multiple markers ( pins ) on google maps with multiple infowindow. Now you will put the code on script tag after the closing of body tag.

<script>
$(function() {
// Asynchronously Load the map API 
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&amp;callback=initialize";
document.body.appendChild(script);
});

function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
     mapTypeId: 'roadmap'
};
                
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_tuts"), mapOptions);
map.setTilt(45);

// Multiple Markers
var markers = JSON.parse(`<?php echo ($markers); ?>`);
console.log(markers);
 
 var infoWindowContent = JSON.parse(`<?php echo ($infowindow); ?>`);       
    
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers &amp; place each one on the map  
for( i = 0; i < markers.length; i++ ) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
        position: position,
        map: map,
        title: markers[i][0]
    });
    
    // Each marker to have an info window    
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infoWindow.setContent(infoWindowContent[i][0]);
            infoWindow.open(map, marker);
        }
    })(marker, i));

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
    this.setZoom(5);
    google.maps.event.removeListener(boundsListener);
});

}
</script>

Here you have got the record. After you have to parse.json this record and pass into markers and infowindows function.

Recommended:- CodeIgniter 4 Pagination Example Tutorial

Step 7 – Start Development server

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

php spark serve

Then Go to the browser and hit below the url.

http://localhost/demo/GoogleMap

Conclusion

In this codeigniter show/add markers and infowindows from database. you have successfully got the records from the database and show/add the markers with infowindows on google map php codeigniter.

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

Recommended Codeigniter Tutorials

Recommended:- Codeigniter 4 PDF Generator Tutorial Example
Recommended:- CodeIgniter 4 First Crud Example Tutorial
Recommended:- CodeIgniter 4 Rest Api Example Tutorial
Recommended:- Codeigniter 4 Login And Registration Tutorial Example
Recommended:- Send Email in CodeIgniter 4 With SMTP
Recommended:- CodeIgniter 4 Ajax Crud with datatables and Bootstrap Modals
Recommended:- Crop and Save Image using jQuery Coppie in Codeigniter 4
Recommended:- Codeigniter 4 Dynamic Dependent Dropdown with Ajax
Recommended:- Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS
Recommended:- Codeigniter 4 Get Latitude and Longitude From Address

Please ask in the comments!

Suport : Cotekno.Com

comments powered by Disqus