Categories
google-maps google-maps-api-3 javascript

Google Maps JS API v3 – Simple Multiple Marker Example

710

Fairly new to the Google Maps Api. I’ve got an array of data that I want to cycle through and plot on a map. Seems fairly simple, but all the multi-marker tutorials I have found are quite complex.

Let’s use the data array from Google’s site for an example:

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]
];

I simply want to plot all of these points and have an infoWindow pop up when clicked to display the name.

0

    1201

    This is the simplest I could reduce it to:

    <!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 id="map" style="width: 500px; height: 400px;"></div>
    
      <script type="text/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>
    

    👨‍💻 Edit/fork on a Codepen →

    SCREENSHOT

    Google Maps Multiple Markers

    There is some closure magic happening when passing the callback argument to the addListener method. This can be quite a tricky topic if you are not familiar with how closures work. I would suggest checking out the following Mozilla article for a brief introduction if it is the case:

    Mozilla Dev Center: Working with Closures

    7

    • 4

      @RaphaelDDL: Yes those parenthesis are needed to actually invoke the nameless function. The arguments need to be passed because of the way JavaScript works (because of closures). See my answer to this question for an example and more info: stackoverflow.com/a/2670420/222908

      Jul 11, 2012 at 22:07

    • Good answer, but it could be simplified further. Since since all markers will have individual InfoWindows and since JavaScript doesn’t care if you add extra properties to an object, all you need to do is add an InfoWindow to the Marker’s properties and then call the .open() on the InfoWindow from itself. I would have posted the change here, but it the modifications were large enough that I posted my own answer.

      Jun 30, 2016 at 3:08


    • Why not use new MarkerClusterer() for massive performance bust? Check out ChirsSwires answer.

      – DevWL

      Jul 19, 2019 at 1:21


    • hi @ Daniel Vassallo, i too have same requiremnt of displaying multiple markers in my ionic angular project. please assist me , i already asked a question on stackoverflow. here is the question link: stackoverflow.com/questions/57985967/…

      – Shaik

      Sep 21, 2019 at 12:57

    • 1

      It works. Thanks. How will you remove markers from google map because you are using single instance of marker and initialize in loop. Please share your thoughts.

      – Kamlesh

      Dec 1, 2019 at 5:06

    64

    Here is another example of multiple markers loading with a unique title and infoWindow text. Tested with the latest google maps API V3.11.

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
            <title>Multiple Markers Google Maps</title>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
            <script src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false" type="text/javascript"></script>
            <script type="text/javascript">
            // check DOM Ready
            $(document).ready(function() {
                // execute
                (function() {
                    // map options
                    var options = {
                        zoom: 5,
                        center: new google.maps.LatLng(39.909736, -98.522109), // centered US
                        mapTypeId: google.maps.MapTypeId.TERRAIN,
                        mapTypeControl: false
                    };
    
                    // init map
                    var map = new google.maps.Map(document.getElementById('map_canvas'), options);
    
                    // NY and CA sample Lat / Lng
                    var southWest = new google.maps.LatLng(40.744656, -74.005966);
                    var northEast = new google.maps.LatLng(34.052234, -118.243685);
                    var lngSpan = northEast.lng() - southWest.lng();
                    var latSpan = northEast.lat() - southWest.lat();
    
                    // set multiple marker
                    for (var i = 0; i < 250; i++) {
                        // init markers
                        var marker = new google.maps.Marker({
                            position: new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()),
                            map: map,
                            title: 'Click Me ' + i
                        });
    
                        // process multiple info windows
                        (function(marker, i) {
                            // add click event
                            google.maps.event.addListener(marker, 'click', function() {
                                infowindow = new google.maps.InfoWindow({
                                    content: 'Hello, World!!'
                                });
                                infowindow.open(map, marker);
                            });
                        })(marker, i);
                    }
                })();
            });
            </script>
        </head>
        <body>
            <div id="map_canvas" style="width: 800px; height:500px;"></div>
        </body>
    </html>
    

    Screenshot of 250 Markers:

    Google Maps API V3.11 with Multiple Markers

    It will automatically randomize the Lat/Lng to make it unique. This example will be very helpful if you want to test 500, 1000, xxx markers and performance.

    6

    • 1

      Be careful when posting copy and paste boilerplate/verbatim answers to multiple questions, these tend to be flagged as “spammy” by the community. If you’re doing this then it usually means the questions are duplicates so flag them as such instead.

      – Kev

      Mar 9, 2013 at 23:43

    • 1

      This will get many pop up infoWindow for each marker and won’t hide the other infoWindow if it’s currently shown. it’s really helpful 🙂

      – Kannika

      Mar 27, 2014 at 3:30

    • @Anup, if you just read the question and comment it would be better. the question is asking “example for multiple marker” whether it is random or your own bla bla.

      Jun 29, 2015 at 13:39

    • Again why not use new MarkerClusterer() for massive performance bust? Check out ChirsSwires answer.

      – DevWL

      Jul 19, 2019 at 1:24

    • 1

      @DevWL, it was answered back in 2013. You are free to update.

      Jul 21, 2019 at 3:10

    41

    I thought I would put this here as it appears to be a popular landing point for those starting to use Google Maps API’s. Multiple markers rendered on the client side is probably the downfall of many mapping applications performance wise. It is difficult to benchmark, fix and in some cases even establish there is an issue (due to browser implementation differences, hardware available to the client, mobile devices, the list goes on).

    The simplest way to begin to address this issue is to use a marker clustering solution. The basic idea is to group geographically similar locations into a group with the number of points displayed. As the user zooms into the map these groups expand to reveal individual markers beneath.

    Perhaps the simplest to implement is the markerclusterer library. A basic implementation would be as follows (after library imports):

    <script type="text/javascript">
      function initialize() {
        var center = new google.maps.LatLng(37.4419, -122.1419);
    
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: center,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
    
        var markers = [];
        for (var i = 0; i < 100; i++) {
          var location = yourData.location[i];
          var latLng = new google.maps.LatLng(location.latitude,
              location.longitude);
          var marker = new google.maps.Marker({
            position: latLng
          });
          markers.push(marker);
        }
        var markerCluster = new MarkerClusterer({map, markers});
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    

    The markers instead of being added directly to the map are added to an array. This array is then passed to the library which handles complex calculation for you and attached to the map.

    Not only do these implementations massively increase client side performance but they also in many cases lead to a simpler and less cluttered UI and easier digestion of data on larger scales.

    Other implementations are available from Google.

    Hope this aids some of those newer to the nuances of mapping.

    3

    • 2

      Thanks, a big big help! There is an order or magnitude difference in performance, by making the google.map data points first and then passing it to the mapping library, in this case MarketCluster to plot. with about 150,000 data points the first post by ‘Daniel Vassallo’ took about 2 mins to load, this 5 seconds. Thanks a bunch ‘Swires’!

      – Waqas

      Apr 15, 2014 at 15:11


    • 1

      I thought this would be a good place for this, I would imagine most peoples first landing on stack when related to Google maps is this page, and there second is ‘why does my map take so long to load’.

      Jun 25, 2014 at 10:51

    • @Monic it’s whatever your data set is, it’s just a placeholder variable.

      Mar 31, 2015 at 8:39