Simplify Multiple Marker Plotting in Google Maps JS API v3
When working with Google Maps JavaScript API, plotting multiple markers can often require complex implementations. This article provides a straightforward solution for beginners who seek to display an array of markers with accompanying info windows.
Problem:
Let's consider an array of locations with their corresponding names, coordinates, and reference values. The aim is to place markers for each location on a map and display an info window with the name upon marker click.
Solution:
HTML and CSS:
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <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>
JavaScript:
var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: new google.maps.LatLng(-33.92, 151.25), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(locations[i][0]); infowindow.open(map, marker); } })(marker, i)); } </script> </body> </html>
Explanation:
Result:
Upon execution, the code generates a Google Map with multiple markers representing the locations from the input array. Clicking on any marker opens an info window displaying its name.
Closure Note:
The code utilizes closures to pass the marker and location index as arguments to the event listener. If unfamiliar with closures, Mozilla's Dev Center offers a helpful guide on the topic.
The above is the detailed content of How Can I Easily Plot Multiple Markers with Info Windows on a Google Map Using the JavaScript API v3?. For more information, please follow other related articles on the PHP Chinese website!