Multiple Marker With Google Maps API

It is a very commune thing nowadays to use APIs. There are great to easily add extra functionalities onto our websites. And today we are going to have a look at the very popular Google Maps API.I recently worked on a project where the client wanted to have a map on a website showing all the different locations where he offers his services. For this, the map needed to have multiple markers in it. Let’s see how I managed to do this.

Getting Things Ready

All you need in terms of HTML is a div which will be used to contain the map. Also, don’t forget to add an ID and a width and height.

HTML

<div id="map_container" style="width:100%; height:500px"></div>

JavaScript

Just before your closing body tag add the following JavaScript. Make sure to replace the values ‘description’, ‘lat’ (latitude) and ‘lng’ (longitude) with your own values. The bellow JavaScript will be used to display the map and add all the defined markers. Each marker will be clickable to show a description.

<script>
function initMap(){
    //Add all your markers in 'markers' var.
    var markers = [
        {
            "description":"Big Ben London",
            "lat":"51.5007292",
            "lng":"-0.1268141"
        },{
            "description":"Piccadilly Circus London",
            "lat":"51.510121",
            "lng":"-0.136357"
        }
    ];

    var mapOptions = {
        zoom        : 10,
        mapTypeId   : google.maps.MapTypeId.ROADMAP
    };
    var bounds = new google.maps.LatLngBounds();
    var infoWindow = new google.maps.InfoWindow();
    //Set the element ID of you're map's container
    var map = new google.maps.Map(document.getElementById('map_container'), mapOptions);

    //Add all the markers
    for (var i = markers.length - 1; i >= 0; i--) {
        var data = markers[i];
        var thisLatLng = new google.maps.LatLng(data.lat,data.lng);
        //Position current marker
        var marker = new google.maps.Marker({
            position:thisLatLng,
            map:map
        });
        bounds.extend(marker.position);
        (function(marker, data) {
            //Add a click event listener to current marker
            google.maps.event.addListener(marker, "click", function(e){
                //Add description content
                infoWindow.setContent(data.description);
                infoWindow.open(map, marker);
            });
        })(marker, data);
    }
    //Center the map view to show all the markers
    map.fitBounds(bounds);
}
</script>

All is left to do is load the Google Maps API using the URL with a callback parameter to execute the initMap function we just created. Replace the [YOUR API KEY HERE] with you Google Maps API key or it won’t work.

<script async defer src="https://maps.googleapis.com/maps/api/js?key=[YOUR API KEY HERE]&v=3.exp&callback=initMap"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *