Google Maps API offers a secure method to insert the map on the web page. Therefore, the exact location can be marked on the Google Map by a marker. Similarly, the marker with InfoWindow will help you to add some information about the location. So, you can enhance multiple markers with InfoWindow to the Map by Google Maps JavaScript API.
Google Maps with multiple markers is handy when you need to add several locations in a single map. Mostly, Google Maps add static markers. But, if you’re going to add dynamic sites from the database, it can be quickly done with PHP and MySQL. Also, you can attach some multiple markers with Info Window to Google Map animatedly from the database with PHP and MySQL. In this tutorial, we will show you how to add custom markers with Info Window to Google Maps dynamically from the database using PHP and MySQL.
In the example code, we will implement the following functionality.
- Embed Google Maps on the website.
- Fetch dynamic locations from the database.
- Add multiple markers with Info Window to the Google Map.
- Fetch dynamic marker icons from the database.
- Change and add custom icon/images to markers.
Get an API Key
An API key is mandatory to use the Google Maps JavaScript API. Therefore, you only need to specify the API key on API call to confirm with Google Maps JavaScript API. So, before you begin to insert Google Map on the website, make an API key on the Google Developers Console.
- Open the Google Developers Console.
- Choose the options project from the Project drop-down menu at the top. If you don’t have an immediate plan, make a new one.
- On the left side in the navigation panel, select the APIs & Services » Credentials.
- In the Credentials page, select Create credentials » API key.
- Make the API key, and a dialogue will appear with a newly created API key.
Copy the API key to use it later in the script on Google Maps JavaScript API request.
Create Database Table
There is a requirement of a table in the database to store the dynamic locations
info and marker images. The following SQL generates a locations table with some primary fields 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, `icon` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Marker icon', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Configuration (dbConfig.php)
You have to use the dbConfig.php
file to link and select the database. Specify the database host ($dbHost
), password ($dbPassword
), username ($dbUsername
), and name ($dbName
) as per your MySQL database credentials.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "allsweb"; // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
Fetch Location and Marker Image Info from Database
By using PHP and MySQL the latitude and longitude are fetched from the database
- To make multiple markers and custom icon information, you have to use the first result set.
- (location, latitude, longitude, and icon image source).
- Use the second result set, to generate the content of the 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"); ?>
SEE ALSO: Autocomplete Address Field using Google Maps JavaScript API with Places Library
Add Multiple Markers with Custom Images
Load the Google Map JavaScript API and specify an API key in the critical parameter.
<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY"></script>
The following JavaScript code adds a lot of markers with custom icons to Google Maps from the database in PHP.
- The initMap() is a custom JavaScript function that initializes Google Maps.
- Define the Google Maps object and attach the Map to the HTML element.
- Fetch the latitude, longitude, and marker icon image URL from the database and generate position array for multiple markers (markers).
- Fetch the location info from the database and generate an array for the content of info windows (
infoWindowContent
). - Add multiple markers with dynamic locations and custom icons to Google Maps.
- Add an info window with dynamic content to the markers.
- Set the zoom level of the Google Map.
Load initMap()
function to initialize the Google Map.
<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(100); // 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'].', "'.$row['icon'].'"],'; } } ?> ]; // 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, icon: markers[i][3], 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 with Custom Marker Icons
Define an HTML element to embed the Google Map with multiple markers and Info Windows on the web page. Specify the element ID (mapCanvas) in the Google Map object.
<div id="mapCanvas"></div>
CSS Code
Use CSS to set the height and weight of the Google map container.
#mapCanvas { width: 100%; height: 650px; }
SEE ALSO: Credit Card Validation using jQuery
Conclusion
Firstly, the Google Map marker icon can be changed using JavaScript. Secondly, use our example script to modify and add a custom image to marker icons in Google Maps. Thirdly, you can add markers and symbols dynamically from the database with PHP and MySQL. And at last, not only the marker but also you can add dynamic content to the info window of the Google Map.
Also, read our previous blog- Autocomplete Address Field using Google Maps JavaScript API with Places Library