Adding Multiple Markers with Info Windows to Google Maps Dynamically from Database

Google Map provides an easy way to mark a location on the map and embed it on the web page. A marker points out a location on the map and an InfoWindow display content in a popup over the map. Add marker with infowindow to Google Map helps to identify the location more accurately with some additional information about the given location.

Multiple markers are very useful to display multiple locations in a single map. You can embed Google Map with multiple markers and info windows using Google Maps JavaScript API v3. In this case, the latitude and longitude of the locations are specified statically in the Google maps object. But if the latitude and longitude are stored in the database, they need to be assigned dynamically in the Google maps object. In this tutorial, we will show you how to add multiple markers with info windows to Google map dynamically from database using PHP and MySQL.

Get an API key

An API key is required to authenticate with Google Maps JavaScript API. On Google Maps JavaScript API call, an API key must include in the key parameter. So, before you begin to embed Google Maps on the web page, create an API key on Google Developer API Console.

Once you got the API key from Google API Console, copy this API key for later use in the script on Google Maps JavaScript API request.

Create Database Table

To store the locations data a table needs to be created in the database. The following SQL creates a locations table with some basic fields (latitude, longitude, location name, and info) in the MySQL 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,
 `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;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL database credentials.

<?php
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

Get Location Info from Database

The latitude and longitude of the multiple locations are fetched from the database using PHP and MySQL.

  • The first result set is used to generate multiple markers info (location, latitude, and longitude).
  • The second result set is used to generate content of info windows.
<?php
// Include the database configuration file
require_once 'dbConfig.php';

// Fetch the marker info from the database
$result $db->query("SELECT * FROM locations");

// Fetch the info-window data from the database
$result2 $db->query("SELECT * FROM locations");
?>

Add Multiple Markers with Info Windows

Load the Google Map JavaScript API and specify an API key in the key parameter.

<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY"></script>

The following JavaScript code adds multiple markers with info windows to Google map from the MySQL database in PHP.

  • The initMap() is a JavaScript function that handles Google Map creation functionality.
  • Initialize Google Maps object to attach the map to the HTML element.
  • Retrieve latitude & longitude from the database and generate position array for multiple markers (markers).
  • Retrieve location info from the database and generate array for info windows content (infoWindowContent).
  • Add multiple markers with dynamic locations to Google Map.
  • Add info window with dynamic content to the markers.
  • Set zoom level of the Google Map.
  • Load initialize the initMap() function.
<script>
function initMap() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };
                    
    // Display a map on the web page
    map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
    map.setTilt(50);
        
    // Multiple markers location, latitude, and longitude
    var markers = [
        <?php if($result->num_rows 0){
            while(
$row $result->fetch_assoc()){
                echo 
'["'.$row['name'].'", '.$row['latitude'].', '.$row['longitude'].'],';
            }
        }
        
?> ]; // Info window content var infoWindowContent = [ <?php if($result2->num_rows 0){
            while(
$row $result2->fetch_assoc()){ ?> ['<div class="info_content">' + '<h3><?php echo $row['name']; ?></h3>' + '<p><?php echo $row['info']; ?></p>' + '</div>'], <?php }
        }
        
?> ];
// Add multiple markers to map var infoWindow = new google.maps.InfoWindow(), marker, i; // Place each marker 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] }); // Add info window to marker google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infoWindow.setContent(infoWindowContent[i][0]); infoWindow.open(map, marker); } })(marker, i)); // Center the map to fit all markers on the screen map.fitBounds(bounds); } // Set zoom level var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) { this.setZoom(14); google.maps.event.removeListener(boundsListener); }); } // Load initialize function google.maps.event.addDomListener(window, 'load', initMap); </script>

Embed Google Map

Define an HTML element to display the Google Map with multiple markers and Info WIndows on the web page. You need to specify the element ID (mapCanvas) in Google Map object.

<div id="mapCanvas"></div>

CSS Code

The following CSS sets the size of the Google map container.

#mapCanvas {
    width: 100%;
    height: 650px;
}

Move Marker Smoothly on Google Map using JavaScript

Conclusion

Google Map with the marker is very useful when you want to display a location on a Map in the web page. The example code provides a simple way to embed Google Map on the website with multiple markers with info windows. You can generate dynamic markers with dynamic info window content and mark locations to the Google map from the database.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

1 Comment

  1. Shane McHugh Said...

Leave a reply

keyboard_double_arrow_up