Introduction to Google Maps Javascript API

Google Maps Javascript API is very easy to use. In this article, we display a map with location markers.

Get an API Key for Google Maps. Use the API Key in the script tag.

<script src="https://maps.googleapis.com/maps/api/js?key=AIz.....zvT9Y">
</script>

Create a map object with few options. Map options include an initial zoom and center location. Specify location using LatLng object having latitude and longitude. Mark few locations on the map. For each location, create a marker using LatLng object. Finally, attach the marker object to the map.

var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(28.6139, 77.2090)
    };

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

// array of location from web api!
locs.forEach(function (loc) {
    var latLng = new google.maps.LatLng(loc.lat, loc.lon);

    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        title: loc.title
    });

    bounds.extend(latLng);
});

map.setCenter(bounds.getCenter());
map.fitBounds(bounds);

LatLngBounds is another useful class. It helps to center the markers within the map. Add all locations to the bounds object. Finally, use the getCenter method to set the map center. The bounds object cover all the markers in the map.

Render the map within a div tag.

<div id="map-canvas" style="width: 560px; height: 560px">
</div>

Troubleshooting problems in Google Maps integration

The enclosing div should have a width and a height

Don’t forget to set the width and height of the enclosing div tag. If not set, Google maps does not render. Use the browser developer tools to view the computed size of the enclosing div tag.

Incompatibility with jQuery selector

jQuery selector cannot be directly used to instantiate a map. jQuery selector returns a list of nodes. Retrieve the node as follows.

var map = new google.maps.Map($("#map-id")[0], mapOptions);

Rendering a map within a hidden element

The map does not render when is it is within a hidden element. Tabs are a common source of this problem. Create the map when tab is shown.

Related Posts

Leave a Reply

Your email address will not be published.