Need a Website Or Web Application Or Any Help In Code , Contact Us: +91 9437911966 (Whatsapp), Note: Paid Service
Students Tutorial app relased. Download Now.

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


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

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.

<html>
<head>
  <title>Login with Instagram</title>
</head>

<body>
	<a href="<?php echo $instURL; ?>">Login with Instagram</a>
</body>

</html>      

Fetch Location and Marker Image Info from Database

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

<?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"); 
?>

Load initMap() function to initialize the Google Map.

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

Add Multiple Markers with Custom Images

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

<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.

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.

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