Skip to Content
PHPCODE
Adding markers to Google Maps from database using PHP
php code / September 18, 2021

The Google Maps API makes it simple to integrate a map on a website. A marker can be used to mark a specific spot on a Google Map. The InfoWindow marker allows you to add some additional information about the location. Using the Google Maps JavaScript API, you may add numerous markers to the Map with InfoWindow.

When you wish to add many locations to a single map, a Google Map with multiple markers is highly beneficial. Static markers are typically added to Google Maps. However, if you wish to add dynamic locations from the database, PHP and MySQL make it simple. With PHP and MySQL, you may dynamically add many markers to Google Map using the Info Window. In this article, we’ll teach you how to use PHP and MySQL to dynamically add custom markers with Info Window to Google Maps.

The following functionality will be implemented in the example code.

Google Maps should be included into the webpage.
Get the database’s dynamic locations.
Add several marks to the Google Map using the Info Window.
Get the database’s dynamic marker icons.
Markers can be changed and custom icons/images can be added.

Obtain an API Key.
To utilise the Google Maps JavaScript API, you’ll need an API key. To authenticate using the Google Maps JavaScript API, you must include the API key in the API call. So, before you start embedding Google Maps on your website, go to the Google Developers Console and create an API key.

To get started, go to the Google Developers Console.
From the Project drop-down menu at the top, choose the project. Make a new project if you don’t already have one.
Select APIs & Services » Credentials from the left navigation pane.
Select Create credentials » API key from the Credentials page.

The API key will be generated, and a dialogue containing the freshly generated API key will display.
Copy the API key for use in the Google Maps JavaScript API request script later.

Make a database table.
A table in the database is required to contain the dynamic location information and marker pictures. In the MySQL database, the following SQL creates a locations table with some basic fields.

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;

Configuring the Database (dbConfig.php)
The dbConfig.php file is used to connect to the database and choose it. According to your MySQL database credentials, specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

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

Obtain information about the location and marker image from the database.
PHP and MySQL are used to retrieve the latitude and longitude from the database.

The first set of results is used to generate information for numerous markers and custom icons (location, latitude, longitude, and icon image source).
The content of the info windows is generated using the second result set.

<?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 Custom Images to Multiple Markers
Load the Google Map JavaScript API and set the key parameter to an API key.

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

In PHP, the following JavaScript code adds several markers with custom icons on a Google Map.

The initMap() function is a JavaScript function that sets up Google Maps.
Create a Google Maps object and link it to the HTML element.
Retrieve the database’s latitude, longitude, and marker icon image URL, and create a position array for numerous markers (markers).
Get information about the location from the database and create an array for the content of the info windows (infoWindowContent).

To a Google Map, add several markers with dynamic placements and a custom icon.
To the markers, add an info box with dynamic content.
Set the Google Map’s zoom level.
To initialise the Google Map, call 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(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>

Add Custom Marker Icons to a Google Map
Create an HTML element that will allow you to integrate a Google Map with numerous markers and Info Windows on your website. In the Google Map object, specify the element ID (mapCanvas).

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

CSS (Cascading Style Sheet)
Set the height and weight of the Google map container with CSS.

Note:

Using JavaScript, you can quickly modify the icon for the Google Map marker. To update and add a custom image to marker icons in Google Maps, use our sample script. With PHP and MySQL, you may dynamically add markers and icons from the database. You can add dynamic content to the Google Map’s info pane in addition to the marker.

PHPCODE © 2024