Adding Multiple Markers To Google Maps From Database PHP Codeigniter

In this Codeigniter tutorial, we will show you how to add multiple markers with infowindows to a Google Map using JavaScript. We will retrieve the marker information from a database using PHP and Codeigniter.

Sometimes, we need to show multiple markers on a Google Map along with additional information such as user names, contact details, and other information. In this tutorial, we will walk you through the steps of adding multiple markers and multiple infowindows to a Google Map.

Codeigniter Google Map

Contents

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create model
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Latest

In this next step, we’re going to download the newest version of Codeigniter. To do this, go to the website Download Codeigniter and get the most up-to-date setup. After you’ve downloaded it, unzip the setup in your local system’s xampp/htdocs/ folder. You can also rename your project folder to whatever you’d like.

Basic Configurations

Now it’s time to do some basic configuration settings on the config.php file. To do this, we’ll navigate to the application/config/config.php file and open it up in a text editor.

set base url like this:-

$config['base_url'] = 'http://localhost/projects/demo';

Create Database With Table

Next, we need to create a database called “demo”. To create the database, open PHPMyAdmin and create a new database with the name “demo”. Once you have created the database, you can use the following SQL query to create a table in your database.

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

Setup Database Credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Create Controller

Now we need to create a controller name Google.php. In this controller we will create some method/function. We will build some of the methods like :

  • Index() – This is used to showing cities markers with infowindow on google map
<?php
 
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Google extends CI_Controller {
 
    public function __construct() {
        parent::__construct();
        // load model
        $this->load->model('Google_model', 'google');
        $this->load->helper(array('url','html','form'));
    }    
 
    public function index() {
        $users = $this->google->get_list();
 
        $markers = [];
        $infowindow = [];
 
        foreach($users 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);
     
        $this->load->view('map_marker',$location);
    }
     
}
?>

In this controller function, we fetch records from the database and create markers and infowindows in the Google.php controller. Once the markers and infowindows have been created, we pass this data to the views.

Create Model

Now go to application/models folder and create a one model name Google_model.php . After create this model put the below query in to model.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
    class Google_model extends CI_Model {
 
        public function __construct()
        {
            $this->load->database();
        }
        
        public function get_list() {
  
        $query = $this->db->get('locations');
        return $query->result();
      
        }
    }
?>

Create Views

Now we 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 - torqueprogramming.co.in</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>Google Maps Multiple Marker(Pins) In Codeigniter</h2></div>
                    <div id="map_wrapper_div">
                        <div id="map_torque"></div>
                    </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>

Implement CSS

In this step we 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_torque {
    width: 100%;
    height: 100%;
}
</style>

Implement JavaScript Code

Finally, we will implement JavaScript code to create a map on web pages and add multiple markers (pins) on Google Maps with multiple infowindows. We will put the code inside a script tag after the closing 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&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 & 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 we have got the record. After we have to parse.json this record and pass into markers and infowindows function.

Start Development Server

For start development server, Go to the browser and hit below the url.

http://localhost/projects/demo/google

Conclusion

In this Codeigniter tutorial, we were able to successfully retrieve records from the database and add markers with infowindows to a Google Map using PHP Codeigniter.

You May Also Like

  1. Delete Query in PHP Codeigniter Framework
  2. Morris Area & Line Chart With Codeigniter Example
  3. Import Data From Excel & CSV to mysql Using Codeigniter
  4. Upload Image/File Into Database Ajax Codeigniter
  5. Codeigniter Server Side Form Validation With Error Message
  6. Codeigniter Single & Multiple Insert Query
  7. How to Implement Hooks in Codeigniter
  8. Codeigniter PDF Generator Tutorial Using Mpdf library

Leave a Reply

Your email address will not be published. Required fields are marked *