Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

How to add Multiple Google Maps Markers using Google Map API JS V3

In today’s tutorial, we are going to show you how you can add multiple markers to a single Google Map. Not just that though, we are also going to show you how to add custom map styles and custom markers to make your map look even better.

I’m just going to go ahead and show the full code we use to do this, then explain what everything does after. So let’s begin…

In our example, we are using the ID map so your HTML will simply look like this:


<div id="map"></div>

The only CSS styles we have added are:


#map {
    position: relative;
    width: 100%;
    height: 350px;
    display: block;
}

Pretty straight forward so far right? If you want a larger map then just increase the height of the #map in your CSS code.

For the Google Map to work, we need to get a Google API Key. If you need instructions on this then visit here.

You will need to include the JavaScript between the before the sript that runs your JS Google Map API code. This will be as follows:


  <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
  type="text/javascript"></script>

If you are using WordPress, then you can register and enqueue as follows:


    wp_register_script('google-js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyBYL8d1Bnuy1b0EwX9iOldIuORnSMSJcjE' );
    wp_enqueue_script('google-js');	

The WordPress code will go in either your theme or child-theme functions.php file if you have one set up.

Now for the JS code…

You will need to call the following code after you load the Google API script mentioned above:


/* Google Map - Contact Us */

if ($("#map").length > 0) {

    function initializeMap() {

        var locations = [
            ['Battersea Park Road', 51.4705666,-0.1728984, 2],
            ['Webbs Road', 51.4575458,-0.165245, 1]
        ];

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            center: new google.maps.LatLng(51.465691,-0.1706737),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        var icon = {
            url: "/wp-content/themes/spectrum/assets/img/map-marker.png",
            scaledSize: new google.maps.Size(70, 70)
        }; 

        var marker = new google.maps.Marker({
            map: map,
            animation: google.maps.Animation.DROP,
            icon : icon
        });            

        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,
                icon : icon
            });

            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(locations[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }

        var styles = [
            {"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}      
        ];
    
        map.setOptions({styles: styles});            
    
    }
    
    initializeMap();    

} 

So first things first... we added if ($("#map").length > 0) { so that it will only run the JS code on pages that call the map. If you allow it to run on any page, you will find yourself with some console errors, that's why we only run the code on pages that contain the map.

Secondly, we created an array of locations here; var locations = [, you can add as many as you like. Here, we include the info window title, the latitude and longitude coordinates which you can obtain from the URL when you click a location on Google Maps, and also the ID of the location, in our case there are only 2.

In our example, we added two markers, so what we did here is set the 'centre' point to a location that is in the centre of both of the locations so they show correctly on the map. The lat/long value for the centre can be defined here: center: new google.maps.LatLng(51.465691,-0.1706737),.

We then added a custom marker as were not a huge fan of the 'basic' google map markers. You will see on this line; url: "/wp-content/themes/spectrum/assets/img/map-marker.png", that we added the path to our custom marker. We also scaled the marker so that it is double the size so it looks awesome on retina ; ) This was defined on the next line here; scaledSize: new google.maps.Size(70, 70).

We then created a for loop which goes through all the locations and adds each of the pointers on the map using the custom icon that we created.

Finally, we decided to change the default styles of the map. It's always nice to customise this and make it unique. You will see we added var styles = [ and included a long line of code to adjust the map styles. Fear not though, this is very easy to do! Simply head to Snazzy Maps, pick a cool style the matches your website then replace the code with the one provided through their website.

What we end up with our example is a Google Map that looks as follows:

SWEET! We nailed it guys. We sure hope this helps you, if you need any assistance, feel free to drop us a comment below.

As always, happy coding!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Join the discussion