Google Maps with Multiple Markers and Info Windows using JavaScript

Google Maps is an easy and best way to display location on the web page. A marker is used to identify a location on Google Maps and an Info Window displays some content over the map. With marker and info window, you can mark a location more efficiently. Also, it helps the user to find a location more accurately.

In the previous tutorial, we had shown you how to add a marker and info window on Google Maps, where you can add only one marker and info window on Google Maps. This tutorial will show you how to add multiple markers with info windows on Google Maps using JavaScript API V3.

Multiple marker features are very useful to show multiple locations on a single map. Using the Google Maps JavaScript API, you can easily add a location map to the web page with multiple markers and info windows. In this example script, we’re going to display multiple markers on Google map and make each marker clickable for displaying the info window.

Google Maps API Key

All requests to Google Maps JavaScript API must include a key parameter in which an API key must be specified. So, before you begin, create an API key on Google Cloud Console.

Follow the below steps to get an API key for Maps JavaScript API:

  • Go to the Google Cloud Console.
  • Create a new project or select an existing project.
  • Click Continue to enable the API and any related services.
  • On the Library page, the Maps JavaScript API service must be enabled.
  • On the Credentials page, click CREATE CREDENTIALS ​» API key to get an API Key. You can also set the API key restrictions as per the webpage URL where this key will be used.
  • Copy this API key to use in the HTML code required in the next step.

You can also see this step-by-step guide to create an API key on Google API Console – How to Get Google Maps JavaScript API Key

Google Maps JavaScript API

Include the Google Map JavaScript API and provide your API Key in the key parameter.

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

Embed Google Map with Multiple Markers and Info Windows

The following code sample shows how to display Google Maps in HTML web page and add multiple markers with infowindows using JavaScript.

JavaScript Code:
The following code initializes google.maps.Map() object to embed Google map with markers and info windows.

  • Create a callback function called initMap() using JavaScript.
  • Initialize google.maps.Map() with selector element (mapCanvas) and pass options (mapTypeId) and assign it to the map object.
  • Specify the latitude and longitude of multiple locations in the markers array.
  • Specify the content of info windows into the infoWindowContent array.
  • Initialize google.maps.InfoWindow() for info windows popup.
  • Loop through the locations (markers) and set the marker position with options (position, map, title, etc.) using new google.maps.Marker().
  • Set content to the info windows on the marker click event using infoWindow.setContent().
  • Assign initMap callback function to window.initMap.
<script>
// Initialize and add the map
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 = [
        ['Brooklyn Museum, NY', 40.671349546127146, -73.96375730105808],
        ['Central Library, Brooklyn, NY', 40.67254944015601, -73.9682162170653],
        ['Prospect Park Zoo, NY', 40.66427511834109, -73.96512605857858],
        ['Barclays Center, Brooklyn, NY', 40.68268267107631, -73.97546296241961]
    ];
                        
    // Info window content
    var infoWindowContent = [
        ['<div class="info_content">' +
        '<h2>Brooklyn Museum</h2>' +
        '<h3>200 Eastern Pkwy, Brooklyn, NY 11238</h3>' +
        '<p>The Brooklyn Museum is an art museum located in the New York City borough of Brooklyn.</p>' + 
        '</div>'],
        ['<div class="info_content">' +
        '<h2>Central Library</h2>' +
        '<h3>10 Grand Army Plaza, Brooklyn, NY 11238</h3>' +
        '<p>The Central Library is the main branch of the Brooklyn Public Library, located at Flatbush Avenue.</p>' +
        '</div>'],
        ['<div class="info_content">' +
        '<h2>Prospect Park Zoo</h2>' +
        '<h3>450 Flatbush Ave, Brooklyn, NY 11225</h3>' +
        '<p>The Prospect Park Zoo is a 12-acre zoo located off Flatbush Avenue on the eastern side of Prospect Park, Brooklyn, New York City.</p>' +
        '</div>'],
        ['<div class="info_content">' +
        '<h2>Barclays Center</h2>' +
        '<h3>620 Atlantic Ave, Brooklyn, NY 11217</h3>' +
        '<p>Barclays Center is a multi-purpose indoor arena in the New York City borough of Brooklyn.</p>' +
        '</div>']
    ];
        
    // 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);
    });
}

window.initMap = initMap;
</script>

HTML Code:
Define an area in HTML code to embed the Google map on the web page. Also, specify an id of the div element and it should be mentioned in Map Object (new google.maps.Map()).

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

CSS Code

Add the following CSS to set the width and height of the Google map container.

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

Add Multiple Markers with Info Windows to Google Maps Dynamically from Database

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

10 Comments

  1. Mahi Said...
  2. Eric Peterson Said...
  3. Ninad Said...
  4. Shawn Said...
  5. Avi Said...
  6. Keithg Said...
  7. Alex Said...
  8. Luke Said...
  9. MeetPlaya Said...
  10. Wesley Said...

Leave a reply

keyboard_double_arrow_up