Creating a map with multiple markers - Google Maps API JavaScript v3 How to add multiple locations on a Google Map in your website.

Creating a map with multiple locations without using a database may be limited but it has its advantages where the number of places is reduced.
When you want to place up to 10 or 15 markers on a Google map in your website, it may be more effective to include it in a variable next to the code that creates the map.
In this article I will not go on the details of creation of maps, markers or infowindow. This information is available in the following articles:

Before you start this tutorial view a demonstration of the map or download the necessary code.

DEMO DOWNLOAD

Defining markers information

First it is necessary to define the position of the marker in the map and the information to be shown in the Info Window.
The information is stored in an array of objects variable called markersData like shown below:

JavaScript /map.jsen.marnoto.com
var markersData = [
  {
      lat: 40.6386333,
      lng: -8.745,
      name: "Camping Praia da Barra",
      address1:"Rua Diogo Cão, 125",
      address2: "Praia da Barra",
      postalCode: "3830-772 Gafanha da Nazaré" // don’t insert comma in the last item of each marker
   },
   {
      lat: 40.59955,
      lng: -8.7498167,
      name: "Camping Costa Nova",
      address1:"Quinta dos Patos, n.º 2",
      address2: "Praia da Costa Nova",
      postalCode: "3830-453 Gafanha da Encarnação" // don’t insert comma in the last item of each marker
   },
   {
      lat: 40.6247167,
      lng: -8.7129167,
      name: "Camping Gafanha da Nazaré",
      address1:"Rua dos Balneários do Complexo Desportivo",
      address2: "Gafanha da Nazaré",
      postalCode: "3830-225 Gafanha da Nazaré" // don’t insert comma in the last item of each marker
   } // don’t insert comma in last item
];

This way of storing information is not the most effective from the viewpoint of performance of the JavaScript code. However what is intended here is to show, in the clearest possible way, how to create a procedure to insert multiple markers on a map.

How to create markers

To enter the previously defined markers on the map it is necessary to create a function (displayMarkers()) that goes through each item in markersData object array  and create the respective marker using the function (createMarker()).
Let's take a look at the code:

JavaScript /map.jsen.marnoto.com
// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers(){

   // this variable sets the map bounds and zoom level according to markers position
   var bounds = new google.maps.LatLngBounds();

   // For loop that runs through the info on markersData making it possible to createMarker function to create the markers
   for (var i = 0; i < markersData.length; i++){

      var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
      var name = markersData[i].name;
      var address1 = markersData[i].address1;
      var address2 = markersData[i].address2;
      var postalCode = markersData[i].postalCode;

      createMarker(latlng, name, address1, address2, postalCode);

      // Marker’s Lat. and Lng. values are added to bounds variable
      bounds.extend(latlng); 
   }

   // Finally the bounds variable is used to set the map bounds
   // with API’s fitBounds() function
   map.fitBounds(bounds);
}

The comments inserted in the code should be sufficient to understand how this function behaves. This function runs on each item in markersData variable and calls createMarker function, passing its information. Additionally the bounds variable stores the position of each marker. This variable will be used as the parameter for fitBounds() function.

Now let’s look at the function createMarker():

JavaScript /map.jsen.marnoto.com
// This function creates each marker and sets their Info Window content
function createMarker(latlng, name, address1, address2, postalCode){
   var marker = new google.maps.Marker({
      map: map,
      position: latlng,
      title: name
   });

   // This event expects a click on a marker
   // When this event is fired the infowindow content is created
   // and the infowindow is opened
   google.maps.event.addListener(marker, 'click', function() {
      
      // Variable to define the HTML content to be inserted in the infowindow
      var iwContent = '<div id="iw_container">' +
      '<div class="iw_title">' + name + '</div>' +
      '<div class="iw_content">' + address1 + '<br />' +
      address2 + '<br />' +
      postalCode + '</div></div>';
      
      // including content to the infowindow
      infoWindow.setContent(iwContent);

      // opening the infowindow in the current map and at the current marker location
      infoWindow.open(map, marker);
   });
}

Markers are added to the map through the variable marker. Additionally, the Info Window content is created for each marker.

These two functions are meaningless by themselves without the function that initializes the creation of the map:

JavaScript /map.jsen.marnoto.com
function initialize() {
   var mapOptions = {
      center: new google.maps.LatLng(40.601203,-8.668173),
      zoom: 9,
      mapTypeId: 'roadmap',
   };

   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   // a new Info Window is created
   infoWindow = new google.maps.InfoWindow();

   // Event that closes the InfoWindow with a click on the map
   google.maps.event.addListener(map, 'click', function() {
      infoWindow.close();
   });

   // Finally displayMarkers() function is called to begin the markers creation
   displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
View example

This example shows how to add multiple markers on a map. There is only one Info Window that will be used for all markers. This means that only one Info Window can be shown at each click on a marker.

Download the necessary files for this example

As usual, all doubts and comments are welcome. Please use the comments section so that all can share on the information.


Miguel Marnoto

My expertise in the Google Maps JavaScript API v3 is a consequence of my enthusiasm about maps and recognition of the importance that Google Maps service has on people lives.

28 comments to ''Creating a map with multiple markers - Google Maps API JavaScript v3"

COMMENT
  1. Thank you, this is so far the best example I found on the net.
    Can you show how to add a link too in the info box:

    Read More

    ReplyDelete
    Replies
    1. Thank you. You may add any html tags in the infobox.

      Delete
  2. I'm using exactly what you've got here, but my map is starting pff at the equator, on the west cost of Africa. Can can I ensure that the map is centred on the populous of the markers?

    ReplyDelete
  3. The best indeed!!!! Thank you (Y)

    ReplyDelete
  4. Copy-paste worked perfectly, thanks Miguel. You saved a lot of my time.

    ajur-veda dot rs /prodajna-mesta/

    ReplyDelete
  5. Thanks a lot!! cleared much of my doubts (Y) :)

    ReplyDelete
  6. Thx for your series about Google maps, It belongs to the best of what I found on net (Im learning about Gmaps). I miss the article about markerclusterer (I want to iplemented it and its really complicated).
    Btw i bookmarked this site and I look forward to new articles :)

    ReplyDelete
  7. I tried adding the custom info window script - to change the background color of the info windows(like the previous tutorial) but it's still shows the default white behind and the large right margin remains.

    ReplyDelete
  8. Hey, Miguel Marnoto.
    Thanks for you help. but I font that map option are not working in this example. can you tell us about that

    ReplyDelete
  9. Hi Miguel Marnoto,
    Can you please tell me the code/idea for displaying multiple marker and updating the markers positions for particular intervals.

    ReplyDelete
  10. This is wonderful, but how about a guide doing this but using markers created from an XML? I have a lot of points, and using an XML is apparently the best way to go about that.

    ReplyDelete
  11. Thanks bro, very helpful, it give me an idea for my experiment with a map that gets a bunch of markers from a DB.

    Regards from Mexico.

    ReplyDelete
  12. Dear,

    Could you please help me adding a style to the map, i cant get it to work with   "var styles = ["
    Thanks in advance.

    ReplyDelete
  13. I downloaded the script and uploaded to my server with no changes and I keep getting this error "Oops! Something went wrong. this page didn't load google maps correctly see the javascript console for technical details."
    It works fine on my pc but not when it's uploaded to the server.

    ReplyDelete
  14. Google map lets all the interested people about a location position in the earth.But many of the businses owners should have their location in the Google map services.Thee are thousands of Google map creation services, but the appropriate services with your required should be selected by your own decision.

    ReplyDelete
  15. Thanks bro . I want show nearly user using facebook messenger on google map by my real time position . What i have to do ??

    Bestregards.

    ReplyDelete
  16. can my theme preclude this google map from being shown on it, cause i tried it manaully is worked and as an iframe it did not work please help me

    ReplyDelete
  17. Very nice tutorial and well written web page. I'm using this to teach a unit on Geolocation and JavaScript in my computer class. Good job!

    ReplyDelete
  18. how to set the color of markers ?

    ReplyDelete
  19. Is there a way of adding clusters to the map please - as discussed here https://developers.google.com/maps/documentation/javascript/marker-clustering ?

    ReplyDelete
  20. hi thanks for this perfect tutorial, but how can i make this responsive?

    ReplyDelete
  21. Greetings from Idaho! I'm bored to tears at work so I decided to check out your blog on my iphone during lunch break. I really like the information you provide here and can't wait to take a look when I get home. I'm amazed at how fast your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .. Anyhow, amazing blog!

    ReplyDelete
  22. Thanks a lot .After applying all methods,your method really worked with huge array of object.Thanks a lot

    ReplyDelete

Note: Only a member of this blog may post a comment.