Codeigniter 4 - Draw Multiple Markers On Google Map Example

Apr 20, 2022 . Admin



Hi Friends,

In this tutorial, I will show you draw multiple markers on google maps in Codeigniter 4. I’m going to show you about leaflet draw multiple markers Codeigniter 4. you'll learn google maps draw route between multiple markers javascript Codeigniter 4. this example will help you draw different route line between multiple markers maps CodeIgniter 4.

this example will help you draw different route lines between multiple marker maps 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: Install Codeigniter 4

This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2: CI Error Handling

in this second 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

So in this step Google maps provide 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 restoration the “unable to connect database: Codeigniter mistakes”, exchange the hostname price for your database’s default array pass the localhost server fee 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: Create Controller Create controller file (GoogleMapController.php) in Controllers folder, then open and add following code in app/Controllers/GoogleMapController.php file. app/Controllers/GoogleMapController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;

class GoogleMapController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    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('/', 'GoogleMapController::showMap');
Step 8: Create 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 - Mywebtuts.com</title>
    <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>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>

        /*------------------------------------------
        --------------------------------------------
        Google Maps
        --------------------------------------------
        --------------------------------------------*/
        $(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 Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/
Output

Now you can check your own.

I hope it can help you...

#Codeigniter 4