Simple Google Maps Multiple Marker Implementation in JavaScript
In this tutorial, we will explore a simplified approach to creating multiple markers on a Google Map.
Overview
For beginners exploring the Google Maps API, it can seem complex to plot multiple markers on a map. This tutorial provides a simple and straightforward solution.
Example Data
Let's use Google's sample data array:
var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], // ... Additional beach locations ];
Creating the Map
First, we initialize a Google Map:
var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: { lat: -33.92, lng: 151.25 }, mapTypeId: google.maps.MapTypeId.ROADMAP });
Creating Markers
To create multiple markers, we iterate through the locations array:
var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: { lat: locations[i][1], lng: locations[i][2] }, map: map }); }
Adding Pop-up InfoWindows
We create an InfoWindow for each marker to display the beach name when clicked:
var infowindow = new google.maps.InfoWindow(); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i));
Complete Result
The full code snippet below includes all the elements needed for the multiple marker functionality:
// HTML with map container <!DOCTYPE html> <html> <head> <title>Google Maps Multiple Markers</title> <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY" type="text/javascript"></script> </head> <body> <div>
By following these steps, you can easily plot multiple markers with pop-up InfoWindows on a Google Map.
The above is the detailed content of How to Easily Implement Multiple Markers with InfoWindows on a Google Map using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!