Google Maps makes it simple to mark a place on a map and embed it in a web page. A marker on the map indicates a place, and an InfoWindow displays material in a popup over the map. The addition of a marker with an infowindow to Google Maps helps to identify the place more precisely by providing some more information about the specified area.
Several markers can be used to show multiple places on a single map. Using Google Maps JavaScript API v3, you can embed a Google Map with multiple markers and information windows. The latitude and longitude of the sites are supplied statically in the Google maps object in this example. However, if the latitude and longitude are saved in the database, they must be dynamically supplied in the Google maps object. In this article, we'll teach you how to dynamically add numerous markers with info windows to Google Maps from a database using PHP and MySQL.
To use the Google Maps JavaScript API, you must have an API key. An API key must be included in the key argument of a Google Maps JavaScript API request. Generate an API key on Developers API Portal before you begin embedding Google Maps on a web page.
Once you've obtained the API key from Google API Console, copy it and paste it into the script for the Google Maps JavaScript API request.
A table in the database must be built to store the location data. In the MySQL database, the following SQL generates a locations table with some basic fields (latitude, longitude, place name, and info).
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;
To connect to and choose the database, utilise the dbConfig.php file. As per your MySQL database credentials, provide 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); }
PHP and MySQL are used to retrieve the latitude and longitude of the various places from the database.
- The first result set is used to create information on numerous markers (location, latitude, and longitude).
- The second set of results is utilised to produce the content of information 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"); ?>
Load the Google Maps JavaScript API and fill in the key argument with an API key.
<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY"></script>
The JavaScript code below adds several markers with information windows to Google Maps from the MySQL database in PHP.
- InitMap() is a JavaScript function that handles Google Maps creation.
- To link the map to the HTML element, initialise the Google Maps object.
- Obtain latitude and longitude from the database and create a position array for many markers (markers).
- Retrieve location information from the database and create an array for the content of the info windows (infoWindowContent).
- Insert several points with dynamic placements to Google Map.
- To the markers, add an info box with dynamic content.
- Configure the zoom level of the Google Map.
- Load the initMap() method and call it.
<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>
Create an HTML element that will display a Google Map with various markers and Info Windows on the web page. In the Google Map object, you must supply the element ID (mapCanvas).
<div id="mapCanvas"></div>
The CSS below determines the size of the Google map window.
#mapCanvas {
width: 100%;
height: 650px;
}
Whenever you want to show a place on a Map on a web page, Google Map with the marker is quite beneficial. The sample code shows how to easily integrate a Google Map with numerous markers and information windows on a website. You can create dynamic landmarks with variable info window information and add places from the database to the Google map.
© ThemesGiant Copyright @2015-2022 | All rights reserved.