Google Maps API Tutorial - beginner to advanced

In this tutorial, you are going to learn:

  • Loading a map with default settings being disabled
  • Adding overlays, such as marker onto a map
  • Choosing your own markers - and animating them.
  • Zooming a map - programmatically
  • Handling map events, such as click
  • Changing the default language

Google Map API - Application Programming Interface - lets you integrate maps on web pages and mobile apps based on the functions defined in a special JavaScript Library. As this particular example, involving one of my favourite cities in the world, shows Google Map API is highly customizable.

Google has recently restricted the use of its Map API.So, you need an API Key, which you can get free of charge for learning purposes from here. Google has allowed this website to use its API without the need of an API key, as this tutorial is currently on the first page of Google search. In addition to the code given here, please add the following lines for the JavaScript section:

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

Kandy, Sri Lanka - the ancient capital

This is the map of Kandy, the central capital of Sri Lanka, a UNESCO World Heritage City as well as a sacred place for Buddhists. Google Maps API lets you customize the map extensively to address particular needs of end users.: the following map has been customized by disabling the default features that usually are on an embedded map on a web page - zooming, panning, choice of map type and street view. Disabling default features brings in clarity to the map; we can add them later depending on our needs.

The code for the above is as follows:

// This is the div element that contains the map.
<div id="Div1" style="width:500px;height:400px;margin-top:10px;margin-bottom:10px;"></div>
// This is the link to Map API JavaScript Library
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
// Initializing functon
function initializeOne() {
var mapPropOne = {
// Coordinates of the centre of the map in terms of latitude and longitude
center: new google.maps.LatLng(7.2964, 80.6350),
// Zoom level
zoom: 8,
// MapID type
mapTypeId: google.maps.MapTypeId.ROADMAP,
// disabling default features
disableDefaultUI: true
};
// Creating a map object
var mapOne = new google.maps.Map(document.getElementById("googleMapOne"), mapPropOne);
}
// Initializing the map object
google.maps.event.addDomListener(window, 'load', initializeOne);
</script>

In the above example, MapTypeID can take the following values:

  • ROADMAP - default for 2d maps
  • SATELLITE - imagery from satellites
  • HYBRID - photographic map, roads and city names
  • TERRAIN - map with mountains, rivers and natural landmarks

 

 

Adding overlays to a Google Map

In addition to getting a basic map on a web page, Google Map API allows you to place overlays on maps to make it more descriptive. Some of the overlays take the following form:

  1. Marker - the most common one
  2. Polyline - a set of straight lines
  3. Polygon - a geometric shape with few lines
  4. Circles or rectangles
  5. Custom overlays - customizable

Let's place some overlays on a map with default setting being disabled.

Placing a Marker:

As you can see, the red marker with a black dot is placed at the centre of the city of Kandy.

The code is as follows:

<div id="Div1" style="width:500px;height:400px;margin-top:10px;margin-bottom:10px;"></div>
<script>
var mapcenterTwo=new google.maps.LatLng(7.2964, 80.6350);
function initializeTwo()
{
var mapPropTwo = {
center:mapcenterTwo,
zoom:5,
disableDefaultUI:true,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var mapTwo=new google.maps.Map(document.getElementById("googleMapTwo"),mapPropTwo);
// Adding a marker
var marker=new google.maps.Marker({
position:mapcenterTwo,
});
marker.setMap(mapTwo);
}
google.maps.event.addDomListener(window, 'load', initializeTwo);
</script>

Animating a Marker:

Markers can be animated in two different ways:

  • Dropping
  • Bouncing

Dropping, however, is hardly noticeable; Bouncing, on the other hand, gives a more emphasis on a location. In the following example, four types of markers are placed - and then programmatically animated.

Kandy, apart from its picturesque nature, is also famous for unique dancers; hence, a Kandyan dancer is used to symbolize the city on the map.

 Default

 Flag

 Pin

 Dancer

The code is as follows:

<script>
var mapcenterThree = new google.maps.LatLng(7.2964, 80.6350);
// Variable to store the source of images
var im;
var markerTwo;
function initializeThree() {
mkrAnimation();
var mappropThree = {
center: mapcenterThree,
zoom:8,
disableDefaultUI:true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapThree = new google.maps.Map(document.getElementById("googleMapThree"), mappropThree);
var markerTwo = new google.maps.Marker({
position: mapcenterThree,
icon: im,
animation: google.maps.Animation.BOUNCE
});
markerTwo.setMap(mapThree);
}
// Creating a marker and choosing an image
function mkrAnimation() {
// Referring to the radio buttons
if (document.getElementById('mrk0').checked) { im = ""; }
else if (document.getElementById('mrk1').checked) { im = "../images/kflag.gif"; }
else if (document.getElementById('mrk2').checked) { im = "../images/kpin.png"; }
else if (document.getElementById('mrk3').checked) { im = "../images/kdancer.png"; }
}
google.maps.event.addDomListener(window, 'load', initializeThree);
</script>

In the above example, the marker bounces. IF you want it to be dropped, Animation:BOUNCE must be changed to Animation:DROP; the effect is hardly noticeable, though. Please note the letters are all uppercase.

 

 

Marking with Circles:

Google Maps API lets you draw circles with specific radii from the centre of the map. It will be useful, especially for walkers, as they can get to know whether there are any landmarks in the circular region that they choose on the map.The radius of the circle can be changed programmatically to address one's needs.

Kandy, the hill capital of Sri Lanka, is surrounded by many sites of archaeological significance. So, a visiting tourist, both local and foreign, will find such a feature immensely useful in planning his exploration.

Radius:   

Change the radius of the circle from the City Centre of Kandy.

The code is as follows:

<script>
var mapcenterFour = new google.maps.LatLng(7.2964, 80.6350);
var markerThree;
// Variable for the values of radius
var ra;
var z;
z = 8;
function initializeFour() {
circleAnimation();
var mappropFour = {
center: mapcenterFour,
zoom: z,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapFour = new google.maps.Map(document.getElementById("googleMapFour"), mappropFour);
var markerThree = new google.maps.Marker({
position: mapcenterFour,
icon: "../images/kdancer.png",
animation: google.maps.Animation.BOUNCE
});
markerThree.setMap(mapFour);
var kandycity = new google.maps.Circle({
center: new google.maps.LatLng(7.2964, 80.6350),
radius: ra,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.4
});
kandycity.setMap(mapFour);
}
// Making a circle
function circleAnimation() {
ra = eval(document.getElementById('radus').value);
switch (ra) {
case 1000:
z = 15;
break;
case 2000:
z = 14;
break;
case 3000:
z = 13;
break;
case 4000:
z = 13;
break;
case 5000:
z = 12;
break;
}
document.getElementById('txtRd').value = ra / 1000 + " km";
}
google.maps.event.addDomListener(window, 'load', initializeFour); </script>

 

 

Zooming a Map

Zooming can be done manually through a JavaScript function. The procedure is as follows:

Zoom: 

The code for the functionality is as follows:

<script>
// Variable to store zoom values
var j;
function initializeFive() {
j = eval(document.getElementById('rng').value);
var mapPropFive = {
center: new google.maps.LatLng(7.2964, 80.6350),
zoom: j,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
var mapFour = new google.maps.Map(document.getElementById("googleMapFive"), mapPropFive);
}
google.maps.event.addDomListener(window, 'load', initializeFive);
</script>

 

 

Map Events

The events associated with Google Map or objects on the map, such as makers and controls, can be easily manipulated programmatically.Here are some of them:

 Click - disable default controls
 Right Click - double zoom level
 Mouse Out - gives coordinates as lat and long

The code for the above is as follows:

<div id="Div1" style="width:400px;height:300px;margin-top:10px;margin-bottom:10px;"></div>
<input type="radio" name="rdoEvnts" id="Radio1" onclick="initializeSix()" /> Click - disable default controls
<input type="radio" name="rdoEvnts" id="Radio2" onclick="initializeSix()" /> Right Click - double zoom level
<input type="radio" name="rdoEvnts" id="Radio3" onclick="alert('Mouseout Event will fire now.'), initializeSix()" /> Mouse Out - gives coordinates as lat and long
<script type="text/javascript">
var a = false;
var aa = 8;
function initializeSix() {
if (document.getElementById('rdoEvnts2').checked) { aa = 16; }
if (document.getElementById('rdoEvnts1').checked) { a = 'true'; aa = 8; }
var mappropsix = {
center: new google.maps.LatLng(7.2964, 80.6350),
zoom: aa,
disableDefaultUI: a
};
var map = new google.maps.Map(document.getElementById('googleMapSix'), mappropsix);
if (document.getElementById('rdoEvnts3').checked) {
google.maps.event.addDomListener(map, 'mouseout', function () {
alert('Coordinates of Kandy: ' + map.getCenter());
}
)
}
}
google.maps.event.addDomListener(window, 'load', initializeSix);
</script>

 

 

Loading the Kandy Map in Five Different Languages

Kandy is a favourite tourist place in the Indian sub continent. It is mainly visited by the Japanese, Chinese, Russians, British and Indians. So, we can make the five languages available as options - asynchronously.

 English

 Japanese

 Russian

 Chinese

 Hindi

 

The code for the above functions is as follows:

<script>
var script;
function initializeSeven() {
var mapPropSeven = {
center: new google.maps.LatLng(7.2964, 80.6350),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
var mapSeven = new google.maps.Map(document.getElementById("googleMapSeven"), mapPropSeven);
}
// function to load the JavaScript source file asynchronously
function loadScript() {
// parameter for languages
var lng;
if (document.getElementById('rdIndia').checked) { lng = 'hi'; }
else if (document.getElementById('rdRussia').checked) { lng = 'ru'; }
else if (document.getElementById('rdChina').checked) { lng = 'zh'; }
else if (document.getElementById('rdJapan').checked) { lng = 'ja'; }
else
{ lng = 'en'; }
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=false' + '&language=' + lng + '&callback=initializeSeven';
document.body.appendChild(script);
}
//Limiting the asynchronous loading of JavaScript function
if (document.getElementById('rdBritain').checked || document.getElementById('rdIndia').checked || document.getElementById('rdRussia').checked || document.getElementById('rdChina').checked || document.getElementById('rdJapan').checked)
{ google.maps.event.addDomListener(widow, 'load', loadScript); }
google.maps.event.addDomListener(window, 'load', initializeSeven);
</script>

Loading a <script> asynchronously creates its own problems, though, because this script overrules the default script - in the head section - that has been loaded at the beginning. So, if you want to study the examples above this, please refresh the page. Efforts have been made not to let it happen, as long as the radio buttons remain idle.

 

 

 

 

Resources at Fingertips

There is a significant selection of tutorials here, covering ASP.Net, HTML5, CSS3 and JavaScript. They are categorized clearly for you to access them easily on any device - desktops/laptops, smartphones and laptops.
There are quite a few of them on HTML5 Canvas and CSS3. In addition, there are tutorials on JavaScript and ASP.Net too.

Email: 

Stand Out - from the crowd

students

"There's no such thing as a free lunch."

The best things in nature are free with no strings attached - fresh air, breathtakingly warm sunshine, scene of meadow on the horizon...

Vivax Solutions, while mimicking nature, offers a huge set of tutorials along with interactive tools for free.

Please use them and excel in the sphere of science education.

Everything is free; not even registration is required.

 

 

Recommended Reading

 

The best book to master HTML5 canvas animations. The author tells you how to manipulate the canvas element with JavaScript in a progressive way - starting from the easier to harder worked examples. It is ideal for anyone who wants to be a game developer in HTML5.

Advertisements

Advertisement