Pusat Ilmu Secara Detil

Displaying markers on google map from database using php

Displaying markers on google map from database using php

In the previous tutorial about creating marker on Google Maps, we have discussed the procedure / stages of creating a marker and multipler marker at a location on google maps.

But all locations in the form of coordinates (latitude, longtitued), the data have defined in the coding, it's mean the location is static.

In this tutorial,we will create a marker at a location or more, where the location data is taken from the database.

The following is the output that we will create, as shown in Figure 1 below:
(Fig.1)

Step by Step Guide: Create Marker From Database

1. Create database
Database creation aims to store location information (latitude, longitude) as well as information once marker is clicked. In this example,the name of database is googlemaps.
CREATE TABLE IF NOT EXISTS `data_location` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `desc` varchar(255) NOT NULL,
  `lat` float(10,6) NOT NULL,
  `lon` float(10,6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

INSERT INTO `data_location` (`id`, `desc`, `lat`, `lon`) VALUES
(1, 'Ibukota Provinsi Aceh', 5.550176, 95.319260),
(2, 'Ibukota Kab.Aceh Jaya', 4.727890, 95.601372),
(3, 'Ibukota Abdya', 3.818570, 96.831841),
(4, 'Ibukota Kotamadya Langsa', 4.476020, 97.952446),
(5, 'Ibukota Kotamadya Sabang', 5.909284, 95.304741);

the above script to create a table named data_location as shown Figure.2:
(Fig.2)
2.Create file connect.php
This file to establish a connection with the database:
<?php
$con=mysqli_connect("localhost","root","","googlemap");
?>

3. Loading the Google Maps JavaScript API
This script is required to connect to Google Maps Services
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
In the sensor paremeter , we set false. This is because we will determine the position of the location itself.

4. Define Google Maps Variables
// Variable to store information (taken from field desc)
var infoWindow = new google.maps.InfoWindow;

//  Variable to set map Roadmap
var mapOptions = {
  mapTypeId: google.maps.MapTypeId.ROADMAP
} 

// Create map
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      
// Variable to declare our bounds object.
var bounds = new google.maps.LatLngBounds();

In step 4, we need to prepare variables to accommodate:
  • Var InfoWindow, used to hold information, later we will store data from field "desc" field from database googlemaps.
  • Var mapOptions, is used to save the  map type RoadMap. Other types of maps that can be supported: SATELLITE (photographic map), HYBRID (photographic map + road and city names), TERRAIN (map with mountains, rivers).
  • Var map, is used to store map objects.
  • Var bounds, is used to declare our bounds object

5. Php script to retrieve data from the database
<?php
    $query = mysqli_query($con,"select * from data_location");
    while ($data = mysqli_fetch_array($query))
    {
        $nama = $data['desc'];
        $lat = $data['lat'];
        $lon = $data['lon'];
        
        echo ("addMarker($lat, $lon, '<b>$nama</b>');\n");                        
    }
 ?>

6. The process of making markers
The data from step 5 will be sent to the function addMarker for making marker.
function addMarker(lat, lng, info) {
    var lokasi = new google.maps.LatLng(lat, lng);
    bounds.extend(lokasi);
    var marker = new google.maps.Marker({
        map: map,
        position: lokasi
    });       
    map.fitBounds(bounds);
    bindInfoWindow(marker, map, infoWindow, info);
 }

7. Displays information on markers that are clicked
function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}

Full Source Code

In this example, we will retrieve data from the database and create a marker for the cities: Banda Aceh, Sabang, Calang, Langsa and Blangpidie. Each city will display  information when one of the markers is clicked.
<?php include "connect.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi Marker Map </title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/ilmudetil.css">
    <script src='assets/js/jquery-1.10.1.min.js'></script>       
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    
    <script>
        
    var marker;
      function initialize() {
        var infoWindow = new google.maps.InfoWindow;
        
        var mapOptions = {
          mapTypeId: google.maps.MapTypeId.ROADMAP
        } 
 
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        var bounds = new google.maps.LatLngBounds();

        // Retrieve data from database
        <?php
            $query = mysqli_query($con,"select * from data_location");
            while ($data = mysqli_fetch_array($query))
            {
                $nama = $data['desc'];
                $lat = $data['lat'];
                $lon = $data['lon'];
                
                echo ("addMarker($lat, $lon, '<b>$nama</b>');\n");                        
            }
          ?>
          
        // Proses of making marker 
        function addMarker(lat, lng, info) {
            var lokasi = new google.maps.LatLng(lat, lng);
            bounds.extend(lokasi);
            var marker = new google.maps.Marker({
                map: map,
                position: lokasi
            });       
            map.fitBounds(bounds);
            bindInfoWindow(marker, map, infoWindow, info);
         }
        
        // Displays information on markers that are clicked
        function bindInfoWindow(marker, map, infoWindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
          });
        }
 
        }
      google.maps.event.addDomListener(window, 'load', initialize);
    
    </script>
    
</head>
<body onload="initialize()">
<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.html">
            Pusat Ilmu Secara Detil</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-left">
                <li class="clr1 active"><a href="index.html">Home</a></li>
                <li class="clr2"><a href="">Programming</a></li>
                <li class="clr3"><a href="">English</a></li>
            </ul>
        </div>
    </div>
</nav>
</br></br></br></br>  
<div class="container" style="margin-top:10px"> 

    <div class="row">
        <div class="col-md-8">
            <div class="panel panel-default">
                <div class="panel-heading">Marker Google Maps</div>
                    <div class="panel-body">
                        <div id="map-canvas" style="width: 700px; height: 600px;"></div>
                    </div>
            </div>
        </div>  
    </div>
</div>  
</body>
</html>

Share this:

You Might Also Like:

Disqus Comments