Add Custom Marker Icons to Google Map Dynamically from the Database with PHP and MySQL

Google Maps API provides an easy way to embed the map on the web page. The specific location can be marked on the Google Map using a marker. The marker with InfoWindow helps to add some information about the location. You can add multiple markers with InfoWindow to the Map using Google Maps JavaScript API.

Google Map with multiple markers is very useful when you want to add multiple locations in a single map. Generally, static markers are added to Google Maps. But, if you want to add dynamic locations from the database, it can be easily done with PHP and MySQL. You can add multiple markers with Info Window to Google Map dynamically 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 required to use the Google Maps JavaScript API. You need to specify the API key on API call to authenticate with Google Maps JavaScript API. So, before you begin to embed Google Map on the website, create an API key on the Google Developers Console.

  • Go to the Google Developers Console.
  • Select the project from the Project drop-down menu at the top. If you don’t have an existing project, create a new one.
  • In the left navigation pane, select the APIs & Services » Credentials.
  • In the Credentials page, select Create credentials » API key.
  • The API key will be created and a dialog will appear with newly created API key.

Copy the API key for later use in the script on Google Maps JavaScript API request.

How to Get Google Maps JavaScript API Key

Create Database Table

To store the dynamic locations information and marker images a table is required in the database. The following SQL creates a locations table with some basic 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)

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

Fetch Location and Marker Image Info from Database

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

  • The first result set is used to generate multiple markers and custom icons information (location, latitude, longitude, and icon image source).
  • The second result set is used 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");
?>

Add Multiple Markers with Custom Images

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 custom icons to Google Map 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 array for the content of info windows (infoWindowContent).
  • Add multiple markers with dynamic locations and custom icon to Google Map.
  • Add info window with dynamic content to the markers.
  • Set 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;
}

Autocomplete Location Search using Google Maps JavaScript API and jQuery

Conclusion

Google Map marker icon can be easily changed using JavaScript. Use our example script to change and add a custom image to marker icons in Google Maps. You can add markers and icons dynamically from the database with PHP and MySQL. Not only the marker but also you can add dynamic content to info window of the Google Map.

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

3 Comments

  1. Kiru Said...
  2. Shashank Varma Said...
  3. Deb Said...

Leave a reply

keyboard_double_arrow_up