Advertisement

Google Maps Web API with Examples

Introduction

Google Maps Web API allows the website to display Google Maps. An API is an Application Programming Interface. This API also provides support for customizing Google Maps along with the information i.e. placing pin etc. Google Maps also provide the library for Android and other platforms as well.

Environment for Google Maps Web API

Google Maps Web API is a JavaScript library. In web pages when you need to consume the services of JavaScript API, you include it with the help of <script> tag.

Load Google Maps API

You can add Google Maps to your web page by adding the source for the script to load.

Initializing the Map

To use Google Maps Web API, you must set initial properties for the Map. Create an initialize() method, and initialize the mapProp object to define the map properties. The mapProp contains the map location with longitude and latitude in LatLng object, zoom level of the map(more the zoom level is, more will be the resolution), and the map type:

1

2

3

4

5

varmapProp={

center:new google.maps.LatLng(33.729388,73.093146),

zoom:10,

mapTypeId:google.maps.MapTypeId.ROADMAP

};

Map Types

Google Maps Web API supports 4 type of Maps:

ROADMAP: Normal or Default 2 Dimensional Maps.

SATELLITE: Photographic Maps.

HYBRID: Photographic maps with roads and city names.

TERRAIN: Map with rivers, mountains, etc.

Display Google Map on Web Page

You will need a container to load Google Maps i.e. a div with some id so that it can be accessed:

1

<div id="map"style="width:500px;height:400px;"></div>

Now, creating the map object and passing container with mapProp will display the map inside the container.

1

varmap=newgoogle.maps.Map(document.getElementById("map"),mapProp);

DOM listener for the map when the page loads.

1

google.maps.event.addDomListener(window,'load',initialize);

Here you go, you can now display the map on any web page.

Complete Code for Simple Map on Web Page

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<!DOCTYPEhtml>

<html>

<head>

<script

src="http://maps.googleapis.com/maps/api/js">

</script>

<script>

functioninitialize(){

varmapProp={

center:new google.maps.LatLng(33.729388,73.093146),

zoom:10,

mapTypeId:google.maps.MapTypeId.ROADMAP

};

varmap=newgoogle.maps.Map(document.getElementById("map"),mapProp);

}

google.maps.event.addDomListener(window,'load',initialize);

</script>

</head>

<body>

<div id="map"style="width:500px;height:400px;"></div>

</body>

</html>

Adding Google Map API key

You can get Google Maps JavaScript API from Google Console. As you get for Android, after creating Google account. For providing your Google API key, Google Maps accepts API key in the key parameter at the time of loading. i.e. ?key=<your API key>.