Google-Map-API-Tutorials-and-Ref by shuifanglj

VIEWS: 736 PAGES: 72

									                 Google Map API
                                  A Complete Reference Guide

                                             Version 3.0




                                                           Efextra eSolutions Private Limited,

                                                                         Sanjay Manu Suman

                                                                                     1|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  Google Map API Tutorials and Reference Guide for Efextra eSolutions Pvt. Ltd.
The easiest way to start learning about the Google Maps API is to see a simple example. The following web
page displays a map centered on Sydney, New South Wales, Australia:

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false"></script>
<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
       zoom: 8,
       center: latlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
  }

</script>
</head>
<body onload="initialize()">
  <div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Even in this simple example, there are a few things to note:

   1.   We include the Maps API JavaScript using a script tag.
   2.   We create a div element named "map_canvas" to hold the Map.
   3.   We create a JavaScript object literal to hold a number of map properties.
   4.   We write a JavaScript function to create a "map" object.
   5.   We initialize the map object from the body tag's onload event.

These steps are explained below.

Loading the Google Maps API

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false"></script>

The http://maps.google.com/maps/api/js URL points to the location of a JavaScript file that
loads all of the symbols and definitions you need for using v3 of the Google Maps API. Your page
must contain a script tag pointing to this URL.



                                                                                              2|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
The <meta> tag within this header specifies that this map should be displayed full-screen and
should not be resizable by the user.

Note that we also need to set a sensor parameter to indicate whether this application uses a sensor
to determine the user's location. We've left this example as a variable set_to_true_or_false to
emphasize that you must set this value to either true or false explicitly.

Map DOM Elements

<div id="map_canvas" style="width: 100%; height: 100%"></div>

For the map to display on a web page, we must reserve a spot for it. Commonly, we do this by
creating a named div element and obtaining a reference to this element in the browser's document
object model (DOM).

In the example above, we define a <div> named "map_canvas" and set its size using style
attributes. Note that this size is set to "100%" which will expand to fit the size on mobile devices.
You may need to adjust these values based on the browser's screensize and padding. Note that the
map will always take its size from that of its containing element, so you must always set a size on
that <div> explicitly.

Map Options

var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
   zoom: 8,
   center: myLatlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
};

To initialize a Map, we first create a Map options object to contain map initialization variables.
This object is not constructed; instead it is created as an object literal. Because we want to center
the map on a specific point, we also create a latlng value to hold this location and pass this into
the map's options. For more information on specifiying locations see Latitudes and Longitudes
below.

We also set the initial zoom level and mapTypeId to google.maps.MapTypeId.ROADMAP. The
following types are supported:

      ROADMAP displays the normal, default 2D tiles of Google Maps.
      SATELLITE displays photographic tiles.
      HYBRID displays a mix of photographic tiles and a tile layer for prominent    features (roads,
       city names).
      TERRAIN displays physical relief tiles for displaying elevation and water features
       (mountains, rivers, etc.).

Unlike in the Google Maps V2 API, there is no default map type. You must specifically set an
initial map type to see appropriate tiles.

                                                                                            3|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
google.maps.Map     - the Elementary Object
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

The JavaScript class that represents a map is the Map class. Objects of this class define a single
map on a page. (You may create more than one instance of this class - each object will define a
separate map on the page.) We create a new instance of this class using the JavaScript new
operator.

When you create a new map instance, you specify a <div> HTML element in the page as a
container for the map. HTML nodes are children of the JavaScript document object, and we obtain
a reference to this element via the document.getElementById() method.

This code defines a variable (named map) and assigns that variable to a new Map object, also
passing in options defined within the myOptions object literal. These options will be used to
initialize the map's properties. The function Map() is known as a constructor and its definition is
shown below:

     Constructor                                   Description
google.maps.Map(            Creates a new map using the passed optional parameters in
opts?)                      the opts parameter.

Loading the Map

  <body onload="initialize()">

While an HTML page renders, the document object model (DOM) is built out, and any external
images and scripts are received and incorporated into the document object. To ensure that our map
is placed on the page after the page has fully loaded, we only execute the function which
constructs the Map object once the <body> element of the HTML page receives an onload event.
Doing so avoids unpredictable behavior and gives us more control on how and when the map
draws.

The body tag's onload attribute is an example of an event handler. The Google Maps JavaScript
API also provides a set of events that you can handle to determine state changes.

Latitudes and Longitudes

We need a way to refer to locations on the map. The google.maps.LatLng object provides such a
mechanism within the Google Maps API. You construct a LatLng object, passing its parameters in
the order { latitude, longitude }:

  var myLatlng = new google.maps.LatLng(myLatitude, myLongitude)

Note: the process of turning an address into a geographic point is known as geocoding. Geocoding
is supported in this release of the Google Maps API.

                                                                                           4|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
LatLng objects have many uses within the Google Maps API. The google.maps.Marker object
uses a LatLng in its constructor, for example, and places marker overlays on the map at the given
geographic location.

Map Types

There are many types of maps available within the Google Maps API. In addition to the familiar
"painted" road map tiles, the Google Maps API also supports other maps types. These map types
are set within the map's Map options object using the mapTypeId property.

The following map types are available in the Google Maps API:

      MapTypeId.ROADMAP displays the default road map view
      MapTypeId.SATELLITE displays Google Earth satellite images
      MapTypeId.HYBRID displays a mixture of normal and satellite views
      MapTypeId.TERRAIN displays a physical map based on terrain information.

You can change a map's map type by calling the map's setMapTypeId() method.




                                                                                        5|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
                               Google Map API Version 3.0
Chapter - 1

The Google Maps API has evolved to version 3. This version is a complete rewrite and focuses
primarily on speed. The new API also features new ways of using it. This article is the first in a
series exploring version 3 of the Google Maps API. This first article will take a look on how to
create a simple map and explain some differences from the previous version.

Background information

First of all, this is an early release of the new API and it‘s still in Labs. It doesn‘t contain all the
features of the old API and will probably never do so since the old API is bloated with lots of
helper methods for doing all sorts of things like making AJAX calls and showing log windows.
Nowadays we have libraries like jQuery and Prototype and tools such as Firebug to take care of
these things. Therefore these features will not be included in the new API, since it‘s main focus is
to be streamlined in order to be as fast as possible. Other missing features such as polygons and
polylines will however probably eventually be included.

Secondly, since it‘s an early release it‘s still undergoing major changes. Features will be added as
we go along and some changes of how to do certain things might be introduced.

That said, I think that the new API is mature enough to use and certainly to experiment with. It
also contains the most common features seen in implementations on Google Maps on the Web.

Enough with the background info already! Let‘s take a look of what the new API looks like.

Inserting a reference to the API

The first thing you will notice is that the API key is no longer necessary. In the previous versions
the API key was inserted as a querystring into the script reference but not so anymore. This means
that you don‘t have to apply for a new API key for every domain you want to have a map at. It also
means that the URI to the API is a lot shorter.

So the only thing you have to tell, while referencing the API, is whether your device has a sensor
or not. sensor=false if you don‘t have a sensor and sensor=true if you do. With a sensor is
meant some way to determine your present location, like if you have a GPS in your device. This
information is attached as querystring at the end of the URI.

   1. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Creating a map

A new namespace

In previous versions of the API there were lots of global variables, distinguishing themselves by
having a capital G in the beginning, like GMap and GLatLng. In the new API the namespace
                                                                                              6|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
google.maps  is used. So what was formerly called GLatLng is now called google.maps.LatLng.
Using namespaces is good coding praxis. One should avoid cluttering the global namespace as
much as possible in order to avoid collisions with other code.

So in practical terms, here‘s how to create a new coordinate object the old way and how to do it the
new way. The LatLng() method takes two arguments, an x and an y coordinate.

   // The old way

   var latlng = new GLatLng(57.8, 14.0);

   // The new way

   var latlng = new google.maps.LatLng(57.8, 14.0);

Object literals

The new API makes heavy use of object literals to pass arguments to it‘s methods. The old API
used object literals as well, but in this version they‘ve taken it a step further which I think is
positive. I think this is a really beautiful way of coding. It‘s easy to use, easy to maintain and easy
to expand. For you who doesn‘t know what an object literal is, it looks like this:

view plaincopy to clipboardprint?

   var myObj = {

     id: '1',

     name: 'Whatever'

   };

   alert(myObj.name); // Will alert Whatever

It‘s basically a fast and easy way to create a Javscript object. Some of you might also recognize it
as JSON, and that‘s exactly what it is. JSON stands for Javascript Object Notation and is in fact a
Javascript Object.

Initializing the map

To initialize the map we need to call the constructor of the Map class. It takes two arguments the
first one being a reference to a HTML elemtn where you want the map to be inserted (often <div
id="map">) and the second one being an object literal (options) containing a set of properties.

This is much like how it works in the old API. The big difference is that in the old API you had to
call the method setCenter() immediately after calling the constructor in order for the map to
display. setCenter() told the map what location would be the center of the map and what the

                                                                                             7|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
initial zoom level would be. In the new API this is not neccesary since both these properties are
passed in the option parameter. So instead of making two calls, you now have to do only one. An
approach that I think makes a lot more sense.

Before we get into the details of what properties option contains, lets have a look at what the code
to create a map looks like.

   // Creating a LatLng object containing the coordinate for the center of the map

   var latlng = new google.maps.LatLng(57.8, 14.0);

   // Creating an object literal containing the properties we want to pass to the map

   var options = {

       zoom: 6,

       center: latlng,

       mapTypeId: google.maps.MapTypeId.ROADMAP

   };

   // Calling the constructor, thereby initializing the map

   var map = new google.maps.Map(document.getElementById('map'), options);

Options

The option parameter is, as mentioned before, an object literal containing the properties we want to
pass to the map object. There are three required properties that must be passed to the map on
initialization. These are:

         center
          This property sets the center of the map and takes a coordinate of the type google.maps.LatLng
         zoom
          This is a number that sets the initial zoom-level of the map
         mapTypeId
          This property sets what kind of map type that would initially be used. The most common type is
          google.maps.MapTypeId.ROADMAP

There are of course lots of other properties that you can use when initializing the map, including
which controls to display and which features to enable or disable. For a full list see the
documentation.




                                                                                                8|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Live example




A live demonstration of a simple map

I‘ve put together a live example of how to add a Google Map v3 on a web page.

Conclusion

In conclusion I would say that the Google Maps API team has done several things right here. First
of all by using a proper namespace, thereby not cluttering the global namespace. Secondly by
heavy use of object literals to pass arguments. This way the API is more consistent and also easier
to expand in future releases.

Please note that the API is still under development and is still undergoing changes. The way it
works might change before the final release.

This is the first article in a series about the Google Maps API V3, so keep your eyes open for the
next one which will explore the different properties for the map object and how you can use these
to make the map behave and look differently.




                                                                                          9|Page
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Chapter – 2

The required properties

As we saw in the last article there are 3 required properties when creating a map. These are:

      center
       Takes a coordinate in the form of a google.maps.LatLng that defines the center of the map
      zoom
       Sets the initial zoom level of the map. It have to be an integer between 0 and 19 where 0 is fully
       zoomed out and 19 is fully zoomed in.
      mapTypeId
       Takes a constant of type google.maps.MapTypeId that defines what the initial map type would
       be

It‘s pretty obvious how the two first properties work, but the last one, mapTypeId, requires a brief
explanation. What it does is to tell the map what kind of map to display by providing it with a
constant. There are a few map types to choose from and they are all contained in the namespace
google.maps.MapTypeId. These are:

      ROADMAP
       A normal map
      SATELLITE
       Satellite images
      HYBRID
       Displays satellite images with roads and labels overlayed on it
      TERRAIN
       Displays a map with physical features such as terrain and vegetation

So for example, constructing a simple map with the maptype SATTELITE is done like this:

       // Creating an object literal containing the properties we want to pass to the map

       var options = {

         zoom: 6,

       center: new google.maps.LatLng(57.8, 14.0),

        mapTypeId: google.maps.MapTypeId.SATTELITE

       };

       // Calling the constructor, thereby initializing the map

       var map = new google.maps.Map(document.getElementById('map'), options);



                                                                                             10 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
That code would produce a map that looks something like this.




Controlling the UI

Note that some user controls are displayed on the map by default. In the old API you had to
explicitly define which controls that would show but in version 3 it works the other way around,
you have to explicitly define which controls not to show.

diableDefaultUI [boolean]

Default value is false. By setting this to true you will disable the default UI. That is: the default
zoom control and the map type chooser will not be displayed, much as the default behavior in the
old API. You can however also enable or disable these controls individually.

mapTypeControl [boolean]

With this property you control whether the mapTypeControl will be displayed or not. The
mapTypeControl is the control positioned in the upper right corner of the map from which you can
choose what map type to show. Set it to true to display it and to false to hide it. The default
value is true.

mapTypeControlOption

With this property you control how the mapTypeControl will be displayed. It can have one of the
following values which all resides in the google.maps.MapTypeControlStyle namespace.

      DEFAULT
       The DEFAULT value will vary the look of the mapTypeControl depending of the size of the window
       and possibly other factors.
      HORIZONTAL_BAR
       This option will display the standard bar.

      DROPDOWN_MENU
       This will display the control as a drop-down list. It can be handy if the map is small or you want it
       to take as little space as possible for some other reason. It currently looks a little weird since the
       arrow is positioned over the text, but I suspect that it’s a temporary glitch that will be fixed in

                                                                                                  11 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
            future releases.


If for example you want this control to display like a drop-down menu you define it like this:

   var options = {

       zoom: 6,

       center: new google.maps.LatLng(57.8, 14.0),

       mapTypeId: google.maps.MapTypeId.ROADMAP,

       mapTypeControlOptions: {

           style: google.maps.MapTypeControlStyle.DROPDOWN_MENU

       }

   };

Note that its parameter is an object literal with one property, style, which takes one of the
constants in google.maps.MapTypeControlStyle as its value. This design might seem a little
cumbersome at first but is actually pretty smart. It makes it easy to add more settings for the map
type control in future releases of the API.

navigationControl [boolean]

This property displays or hides the navigation control. That is the control that typically resides in
the upper left part of the map with which you can zoom and sometimes pan the map. Its
appearance has changed a bit since the old version of the API but essentially works the same way.
The major difference being that in the old API the large control had a ―reset‖ button that reset the
map to its initial state. This feature has been dropped in the new API for unknown reasons.

navigationControlOptions

The style of the navgationControl comes in 4 flavors that all resides in the
google.maps.NavigationControlStyle namespace. These are:

           DEFAULT
            If set to this value, the control will vary according the map size and other factors. As of now that
            means that it will either display the small or the large control but that might change in future
            releases.
           SMALL
            This is the small control that only lets you to zoom the map.




                                                                                                      12 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
           ANDROID
            This control looks like the SMALL one, but is supposed to be specifically tailored for the Android
            mobile platform.
           ZOOM_PAN
            This is the large control that lets you to both zoom and pan the map.




Here‘s some example code on how to display the large control (zoom_pan).

   var options = {

       zoom: 6,

       center: new google.maps.LatLng(57.8, 14.0),

       mapTypeId: google.maps.MapTypeId.ROADMAP,

       navigationControlOptions: {

           style: google.maps.NavigationControlStyle.ZOOM_PAN

       }

   };




                                                                                                    13 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
scaleControl [boolean]

This property determines whether the scale control will be displayed or not. Set it to true to
display the control and false to hide it. This control is not displayed by default, so if you want it
to show you have to explicitly set this property to true.

The scale control is typically positioned in the lower left corner of the map and are used to get a
sense of the scale of the map. It looks like this:



scaleControlOptions

You can control how the scale control will be displayed with the help of this property. It currently
only has one option which is STANDARD so there‘s really not much you can do, but this might
change in future releases.

keyboardShortcuts [boolean]

There are some keyboard shortcuts for controlling the map. These are the arrowkeys for panning
and +/- for zooming.

Default value is true. If set to false it will disable the keyboard shortcuts.

Map div behavior

The Map div is the HTML element that contains the map. Typically it‘s a <div> with id="map" or
something similar. There are some properties that controls the behavior of this.

noClear [boolean]

The default setting of this is false, and what it does is to clear the content of the div that contains
the map. If set to true it will not clear the initial content of it.

backgroundColor [string]

This property also affects the map div. It sets the color of the div‘s background which shows when
you pan the map and before the map tiles have been loaded.

noResize [boolean]

Default value is false. If set to true it prevents the map from doing automatic resize checking.

Cursor behavior

Finally there are a couple of properties to control how the cursor will look like. These are:

                                                                                             14 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
draggableCursor

Sets the name or URL of the cursor that is displayed on a draggable object.

draggingCursor

Sets the name or URL of the cursor that is displayed when an object is dragged.

Note: As of the time of writing these properties doesn‘t seem to work properly. This will hopefully
be fixed in a near future.

Live Demo

I‘ve put together a Live Demo where you can try out some of the properties of the map and see
how they affect it.




Try out the Live Demo

Conclusion

In this article we‘ve examined the properties available when initializing a map in Google Maps
API 3. These properties affect the look and behavior of the map. There are additional methods that
can be used to alter these properties, but they will be covered in a future article. In the next article
we will look at how to work with markers in the new API.
                                                                                            15 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Chapter – 3

The marker object

The marker object resides in the google.maps.Marker namespace and takes a single argument,
options. Options is an object literal called Marker options that can have several properties of
which two are required:

        map [Map]
         Map is a reference to the map where you want to add the marker.
        position [LatLng]
         This property indicates the position of the marker and is of type google.maps.LatLng

Lets start by creating a map and adding a regular marker with the standard look and behavior. If
you‘ve read the prior articles in this series you should already be familiar with the code that creates
the map. Please note that I‘ve used a somewhat more compact syntax here than in previous
examples.

   // Creating a map

   var map = new google.maps.Map(document.getElementById('map'), {

       zoom: 7,

       center: new google.maps.LatLng(56.83, 15.16),

       mapTypeId: google.maps.MapTypeId.ROADMAP

   });

   // Creating a marker and positioning it on the map

   var marker = new google.maps.Marker({

       position: new google.maps.LatLng(56.8848, 14.7730),

       map: map

   });

This code would result in a marker being added to the map, incidentally marking the place where I
work. Note that the marker is immediately added to the map upon creation. So there‘s no need, like
in the old API, to explicitly add it to the map after it has been created.




                                                                                           16 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Adding a tooltip

A common thing one might want to do is to add a tooltip to the marker. The tooltip is displayed
when a user hovers with the mouse pointer over the marker. This is easily done by adding the
property title to the marker options object.

Since this marker won‘t be clickable I want to somehow indicate this. That is done by setting the
property clickable to false. This results in that the mouse cursor won‘t change on hover.

   var marker = new google.maps.Marker({

     position: new google.maps.LatLng(56.8848, 14.7730),

     map: map,

     title: 'My workplace',

     clickable: false

   });

Here‘s how this will look like on the map.




                                                                                        17 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Definition

         title [string]
          Sets the tooltip of the marker.
         clickable [boolean]
          Defines whether the marker is clickable/draggable or not. If set to false it will not display a
          special mouse cursor on hover. Default value is true.

Changing the default marker icon

Often we want to use a different marker than the default one. The API offers a simple way of
doing this with the property icon. Icontakes either an URL pointing to an image or a MarkerIcon
as its value. In this example I will use the more simpler, URL, and point it to this image.




This icon is taken from Nicolas Mollet‘s map icon set at http://code.google.com/p/google-maps-
icons/. There‘s lots of similiar icons that you can use.

Here‘s the code for creating a marker with a custom marker icon.

   var marker = new google.maps.Marker({

       position: new google.maps.LatLng(56.8848, 14.7730),

       map: map,

       title: 'My workplace',

       clickable: false,

       icon: 'http://google-maps-icons.googlecode.com/files/factory.png'


                                                                                                  18 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
   });

Now the map and the marker will look like this:




There are some other properties for more advanced control of the marker icon, such as shadow and
shape. Shadow defines the shadow cast by the icon and shape defines the clickable/draggable area
of the marker but I will not explain them further in this article.

Definition

        icon [string|MarkerImage]
         Defines the marker icon. It can either be an URL pointing to a suitable image or an object of type
         MarkerImage.
        shadow [string|MarkerImage]
         Sets the shadow of a marker icon. Takes either an URL or a MarkerImage as its value.
        shape [object]
         Defines the clickable/draggable area of a marker. It takes an object as its value. The object
         contains coordinates that define a polygon much the same way an imageMap is defined.
        flat [boolean]
         If set to true disables the shadow of the marker.

Note: By explicitly setting icon, the property shadow is reset. So even if we don‘t provide shadow
with a value, it will not inherit the shadow of the default marker. I could be argued that in this case
the property flat should be set to true, but it‘s not necessary for the marker to not have a shadow.

Other properties

Additionally there are a few other properties you can use to control the marker.

        cursor [string]
         This property changes the way the cursor look when the mouse pointer hovers over the marker.



                                                                                                19 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
      visible [boolean]
       This property determains if the marker should be visible or not. Set it to false to make the
       marker invisible. The default value is true.
      zIndex [number]
       Sets the stack order of markers. Could be handy if several markers sits on top of each other.

Live demo




Be sure to checkout the Live Demo to see the code shown in this article in action.

Other resources

For a full and most recent definition of the marker object check out the API reference. Also check
out the section about overlays in the documentation.




                                                                                              20 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Chapter – 4

The InfoWindow object

The InfoWindow object will open an InfoWindow somewhere on a map. It looks like a speech
bubble and the tip of its stem typically points to a certain object on the map. Often it‘s pointing at a
marker, but it doesn‘t have to be. It can point at any other object or any coordinate on the map.

The object resides in the google.map.InfoWindow namespace and takes an optional argument
which is options. Options is an object literal in which you can define all the properties for the
InfoWindow. This means that you can create an empty InfoWindow object for later use, but most
of the time you‘ll probably want to fill it with some sort of content right away. To fill it with
content you‘ll need to use the property content. It can be set either on creation of the object or
afterwards using the setContent() method. It can be either a text string, a string containing
HTML, or a reference to an existing HTML node.

Setting the scene

We will start with a map with one marker on it. If you don‘t know how to create a map and add
markers to it, I suggest that you read the previous articles in this series first.

For those of you that are already familiar with the concepts, here‘s the code for creating a map and
adding a marker to it:

   // Creating an option object for the map

   var options = {

        zoom: 7,

        center: new google.maps.LatLng(56.83, 15.16),

        mapTypeId: google.maps.MapTypeId.ROADMAP

   };

   // Initializing the map

   var map = new google.maps.Map(document.getElementById('map'), options);

   // Creating a marker

   var marker = new google.maps.Marker({

     position: new google.maps.LatLng(56.8848, 14.7730),

     map: map,

                                                                                            21 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
     title: 'My workplace'

   });

This will result in a map that looks like this:




Adding an InfoWindow

Now that we have the scene set, lets add an InfoWindow to it. In this example we will instantly fill
the InfoWindow with some content, in this case the classic text string ―Hello world‖:

   // Creating an InfoWindow object

   var infowindow = new google.maps.InfoWindow({

     content: 'Hello world'

   });

Showing the InfoWindow

We have now created an InfoWindow object but not yet added it to the map. To make it appear we
have to first open it and that‘s done with its method open(). This method takes two arguments: the
map object which it will be added to and optionally an anchor where it will point to. The anchor
must be an object on the map that exposes a position property. As of now this will probably be a
marker.

If you don‘t pass on the second argument you must provide the InfoWindow object with a position.
This is done with either the attribute position in options or via its setPosition() method. In this
example however, we will pass our marker as the second argument so that the InfoWindow will
point straight at it.

   1. infowindow.open(map, marker);
                                                                                         22 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Now the InfoWindow will be visible on the map and will look like this:




Note that the default behavior of the map is that it pans so that all of the InfoWindow is visible.
This behavior can be overridden by setting the property disableAutoPan to false.

Adding a click event

As of now our InfoWindow is automatically opened when our map loads. Most of the time we
want it to open when something is clicked and that‘s exactly the functionality we‘re going to add
next. We‘re going to add a click event to the marker so that when it‘s being clicked the
InfoWindow will open.

To add an event to the marker we will need to use the addListener() method found in
google.maps.event. This method takes 3 arguments, the first one being the object it will be
attached to, in this case the marker. The second argument defines what kind of event we want to
add, in this case a click event. The third argument is a function which will be called when the event
is being triggered. In this case we will use an anonymous function and we will move the code that
opens the InfoWindow inside it.

Doing that the code will look like this:

   google.maps.event.addListener(marker, 'click', function() {

     infowindow.open(map, marker);

   });

Now, when we load our page the InfoWindow will not be visible until we click the marker. Then it
will pop up.




                                                                                           23 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Using multiple InfoWindows

You may have noticed that we create the InfoWindow outside the click event of the marker.
Perhaps you‘re thinking that we might as well could have put all of the code regarding the
InfoWindow inside it. But there‘s a good reason for not doing that. By creating the InfoWindow
outside the event handler, we ensure that there only exists one InfoWindow at a time. If we had put
the code for creating the InfoWindow inside the event handler we would have created a new
InfoWindow each time the marker was clicked. Leaving us with several identical InfoWindows on
top of each other.

Now there are ways to deal with this. We could for example check if the InfoWindow existed
before creating it, but by creating it only once we completely avoid the problem all together.

If you‘ve been programming in version 2 of the Google Maps API you‘ll notice a significant
difference here. In the old API we could only have one InfoWindow at a time, but now we can
have several. Because of this we have to change how we think about them. There might be
occasions when we want to display several of them at once, but often we will only want to display
them one at a time.

More control over the Info Window

There are some other properties that you can add to options for added control of the InfoWindow.
I‘ve already mentioned content which defines what will be displayed inside of it and position
which in lack of an anchor defines the position of the InfoWindow. But here‘s all of the properties
available for controlling the look and behavior of the InfoWindow:

content

This property defines the content of the InfoWindow. It can be either plain text, HTML or a
reference to an existing HTML element. The InfoWindow will automatically adjust its size to fit
the content.

disableAutoPan [boolean]

If set to true the map is no longer automatically panned to fit the InfoWindow. Default value is
false.

maxWidth [number]

Sets the maximum width of the InfoWindow in pixels. It must be set before the InfoWindow is
opened.

Another way of controlling the size of the InfoWindow is to add HTML with certain dimensions to
it. This way you can control its size from you CSS.




                                                                                        24 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
pixelOffset [size]

If position is used to place the InfoWindow, pixelOffset defines how far away from this point the
window should be positioned.

position [LatLng]

Defines the position the InfoWindow should be pointing at. If an anchor (the second argument of
the open() method is set, it will override this property.

zIndex [number]

When displaying multiple InfoWindows at the same time, this property will determine the stack
order of those.

Live demo




Check out the Live Demo showing the example used in this article.

Hopefully this article has provided you with a basic understanding of how to use InfoWindows in
your maps but there are a lot more that can be done with them. They still lack a lot of the

                                                                                       25 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
functionality found in the old API, like displaying a detail map inside it or having tabbed content.
Some of these features will probably never find its way into the new API but fortunately it‘s quite
easy to build this functionality yourself. Keep your eyes open for my upcoming book where I will
explain how to do some of this stuff.

Draggable markers

We added draggable markers as a hidden feature in revision 2.46, but today they are making their
official debut as part of the Maps API. To make a marker draggable, set the marker option
draggable to true when you declare it: var marker = new GMarker(center, {draggable:
true});.

When you drag the marker, a little X will appear to mark the spot where the marker will fall. After
you let go of the marker, it bounces into place (to let you know how much fun it's having). If you
prefer non-bouncy markers, set the marker option bouncy to false.

GTileLayerOverlays

The Maps API has GTileLayers (which you can use to build GMapTypes) and GOverlays (which
you can show on top of a Google Map). Today we're introducing GTileLayerOverlays, which lets
you add tile layers without needing to introduce new map types. You can also add & remove them
on the fly, unlike map types.

For example, to create a desaturated map, you can overlay it with a white tile overlay at 50%
opacity:


 var tilelayer = new GTileLayer(new GCopyrightCollection(), 0, 17);
 tilelayer.getTileUrl = function(tile, zoom) {
    // A more interesting tile server would do something with the numbers
    // tile.x, tile.y and zoom.
    return "http://kml.lover.googlepages.com/white_map_tile.gif";
 };
 tilelayer.getOpacity = function() {return 0.5;}
 map.addOverlay(new GTileLayerOverlay(tilelayer));




                                                                                         26 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
                               Detailed Content Begins:
Map Events Overview
JavaScript within the browser is event driven, meaning that JavaScript responds to interactions by
generating events, and expects a program to listen to interesting events. The event model for the
Google Maps API V3 is similar to that used in V2 of the API, though much has changed under the
hood. There are two types of events:

      User events (such as "click" mouse events) are propagated from the DOM to the Google Maps API.
       These events are separate and distinct from standard DOM events.
      MVC state change notifications reflect changes in Maps API objects and are named using a
       property_changed convention

Each Maps API object exports a number of named events. Programs interested in certain events
will register JavaScript event listeners for those events and execute code when those events are
received by registering addListener() event handlers on the google.maps.event namespace.
Developers of V2 of the Google Maps API will be familiar with this usage.

UI Events
Some objects within the Maps API are designed to respond to user events such as mouse or
keyboard events. A google.maps.Marker object can listen to the following user events, for
example:

      'click'
      'dblclick'
      'mouseup'
      'mousedown'
      'mouseover'
      'mouseout'

These events may look like standard DOM events, but they are actually part of the Maps API.
Because different browsers implement different DOM event models, the Maps API provides these
mechanisms to listen for and respond to DOM events without needing to handle the various cross-
browser peculiarities. These events also typically pass arguments within the event noting some UI
state (such as the mouse position).

MVC State Changes
MVC objects typically contain state. Whenever an object's property changes, the API will fire an
event that the property has changed. For example, the API will fire a zoom_changed event on a
map when the map's zoom level changes. You can intercept these state changes by registering
addListener() event handlers on the event namespace method as well.

User events and MVC state changes may look similar, but you generally wish to treat them
differently in your code. MVC events, for example, do not pass arguments within their event. You
                                                                                         27 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
will want to inspect the property that changed on an MVC state change by calling the appropriate
getProperty method on that object.

Map Events

You register for event notifications using the addListener() event handler. That method takes an
object, an event to listen for, and a function to call when the specified event occurs.

The following code mixes user events with state change events. We attach an event handler to a
marker that zooms the map when clicked. We also add an event handler to the map for changes to
the 'zoom' property and move the map to Darwin, Northern Territory, Australia on receipt of the
zoom_changed event:

var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, 'zoom_changed', function() {
      setTimeout(moveToDarwin, 3000);
    });

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title:"Hello World!"
    });
    google.maps.event.addListener(marker, 'click', function() {
      map.setZoom(8);
    });
}

function moveToDarwin() {
  var darwin = new google.maps.LatLng(-12.461334, 130.841904);
  map.setCenter(darwin);
}

Note: If you are trying to detect a change in the viewport, be sure to use the specific
bounds_changed event rather than constituent zoom_changed and center_changed events.
Because the Maps API fires these latter events independently, getBounds() may not report useful
results until after the viewport has authoritatively changed. If you wish to getBounds() after such
an event, be sure to listen to the bounds_changed event instead.

Accessing Arguments in UI Events
UI events within the Google Maps API V3 typically pass an event argument, which can be
accessed by the event listener, noting the UI state when the event occurred. For example, a UI
                                                                                        28 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
'click'   event typically passes a Mouse event containing a latLng property denoting the clicked
location on the map and a pixel argument denoting the screen coordinates of the clicked location.
Note that this behavior is unique to UI events; MVC state changes do not pass arguments in their
events.

You can access the event's arguments within an event listener the same way you would access an
object's properties. The following example adds an event listener for the map, and creates a marker
when the user clicks on the map at the clicked location.

var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    google.maps.event.addListener(map, 'click', function(event) {
      placeMarker(event.latLng);
    });
}

function placeMarker(location) {
  var clickedLocation = new google.maps.LatLng(location);
  var marker = new google.maps.Marker({
      position: location,
      map: map
  });

    map.setCenter(location);
}

Using Closures in Event Listeners
When executing an event listener, it is often advantageous to have both private and persistent data
attached to an object. JavaScript does not support "private" instance data, but it does support
closures which allows inner functions to access outer variables. Closures are useful within event
listeners to access variables not normally attached to the objects on which events occur.

The following example uses a function closure in the event listener to assign a secret message to a
set of markers. Clicking on each marker will review a portion of the secret message, which is not
contained within the marker itself.

var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

                                                                                        29 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  // Add 5 markers to the map at random locations
  var southWest = new google.maps.LatLng(-31.203405,125.244141);
  var northEast = new google.maps.LatLng(-25.363882,131.044922);
  var bounds = new google.maps.LatLngBounds(southWest,northEast);
  map.fitBounds(bounds);
  var lngSpan = northEast.lng() - southWest.lng();
  var latSpan = northEast.lat() - southWest.lat();
  for (var i = 0; i < 5; i++) {
    var location = new google.maps.LatLng(southWest.lat() + latSpan *
Math.random(),
        southWest.lng() + lngSpan * Math.random());
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    var j = i + 1;
    marker.setTitle(j.toString());
    attachSecretMessage(marker, i);
  }
}

// The five markers show a secret message when clicked
// but that message is not within the marker's instance data

function attachSecretMessage(marker, number) {
  var message = ["This","is","the","secret","message"];
  var infowindow = new google.maps.InfoWindow(
      { content: message[number],
        size: new google.maps.Size(50,50)
      });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
}

Getting and Setting Properties With in Event Handlers
None of the MVC state change events in the Maps API event system pass arguments when the
event is triggered. (User events do pass arguments which can be inspected.) If you need to inspect
a property on an MVC state change, you should explicitly call the appropriate getProperty()
method on that object. This inspection will always retrieve the current state of the MVC object,
which may not be the state when the event was first fired.

Note: explicitly setting a property within an event handler which responds to a state change of that
particular property may produce unpredictable and/or unwanted behavior. Setting such a property
will trigger a new event, for example, and if you always set a property within this event handler,
you may end up creating an infinite loop.

In the example below, we set up an event handler to respond to zoom events by bringing up an info
window displaying that level. We also check whether the map is fully zoomed-out and zoom in to
zoom level 17 if so.
                                                                                         30 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
var map;
function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var zoomLevel;
    var infowindow = new google.maps.InfoWindow(
      { content: 'Zoom Level Test',
          size: new google.maps.Size(50,50),
          position: myLatlng
      });
    infowindow.open(map);

    google.maps.event.addListener(map, 'zoom_changed', function() {
      zoomLevel = map.getZoom();
      infowindow.setContent("Zoom: " + zoomLevel);
      if (zoomLevel == 0) {
        map.setZoom(10);
      }
    });
}

Controls Overview
The maps on Google Maps contain UI elements for allowing user interaction through the map.
These elements are known as controls and you can include variations of these controls in your
Google Maps API application. Alternatively, you can do nothing and let the Google Maps API
handle all control behavior.

The Maps API comes with a handful of built-in controls you can use in your maps:

       The Navigation control displays a large pan/zoom control as used on Google Maps. This control
        appears in the top left corner of the map. You can adjust the size of this control within the Map
        options object upon setup.
       The Scale control displays a map scale element. This control is not enabled by default.
       The MapType control lets the user toggle between map types (such as ROADMAP and SATELLITE).
        You can adjust the behavior of this control through the Map options object upon setup.

Not all of these controls are enabled by default. To learn about default UI behavior (and how to
modify such behavior), see The Default UI below.

The Default UI
Rather than specifying and setting up individual controls, you may simply wish to specify that
your map exhibit the look and feel of the Google Maps interface, (including any new features or
controls that get added in the future). To get this behavior, you need do nothing. Your map will
show up with default controls.
                                                                                            31 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
The Default Control Set

The Maps API provides the following default controls:

 Control           Large Screens              Small Screens              iPhone         Android

             Large Pan/Zoom for sizes   Small Mini-Zoom for sizes
Navigation                                                          Not present    "Android" control
             larger than 400x350px      smaller than 400x350px

                                                                    Same as        Same as
        Horizontal Bar for screens Dropdown for screens
MapType                                                             Large/Small    Large/Small
        larger than 320px wide     smaller than 320px wide
                                                                    Screens        Screens

Scale        Not present                Not present                 Not present    Not present


Additionally, keyboard handling is on by default on all devices.

Disabling the Default UI

You may instead wish to turn off the API's default UI settings. To do so, set the Map's
disableDefaultUI property (within the Map options object) to true. This property disables any
automatic UI behavior from the Google Maps API.

The following code disables the default UI entirely:

function initialize() {
  var myOptions = {
    zoom: 4,
    center: new google.maps.LatLng(-33, 151),
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
       myOptions);
}

Adding Controls to the Map

You may wish to tailor your interface by removing, adding, or modifying UI behavior or controls
and ensure that future updates don't alter this behavior. If you wish to only add or modify existing
behavior, you need to ensure that the control is explicitly added to your application.

Some controls appear on the map by default while others will not appear unless you specifically
request them. Adding or removing controls from the map is specified in the following Map
options object's fields, which you set to true to make them visible or set to false to hide them:



                                                                                         32 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
{
    navigationControl: boolean,
    mapTypeControl: boolean,
    scaleControl: boolean
}

Note that the Maps API V3 does not currently allow you to dynamically add or remove controls.
These must be set upon creation of the map through a Map options object.

The following example sets the map to hide the navigation control and display the scale control.
Note that we do not explicitly disable the default UI, so these modifications are additive to the
default UI behavior.

function initialize() {
  var myOptions = {
    zoom: 4,
    center: new google.maps.LatLng(-33, 151),
    navigationControl: false,
    scaleControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                  myOptions);
}

Control Options
Several controls are configurable, allowing you to alter their behavior or change their appearance.
The Navigation control, for example, may display as either a large control with a full zoom
control and panning controls as shown on Google Maps, or as a smaller, mini-zoom control for
smaller devices.

These controls are modified by altering appropriate control options fields within the Map options
object. For example, options for altering the Navigation control are named
navigationControlOptions.

The Navigation control may appear in one of the following style options:

       google.maps.NavigationControlStyle.SMALL displays a mini-zoom control, consisting of
        only + and - buttons. This style is appropriate for mobile devices.
       google.maps.NavigationControlStyle.ZOOM_PAN displays the standard zoom slider
        control with a panning control, as on Google Maps.
       google.maps.NavigationControlStyle.ANDROID displays the small zoom control as used
        on the native Maps application on Android devices.
       google.maps.NavigationControlStyle.DEFAULT picks an appropriate navigation control
        based on the map's size and the device on which the map is running.

The MapType control may appear in one of the following style options:



                                                                                         33 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
      google.maps.MapTypeControlStyle.HORIZONTAL_BAR displays the array of controls as
       buttons in a horizontal bar as is shown on Google Maps.
      google.maps.MapTypeControlStyle.DROPDOWN_MENU displays a single button control
       allowing you to select the map type via a dropdown menu.
      google.maps.MapTypeControlStyle.DEFAULT displays the "default" behavior, which
       depends on screen size and may change in future versions of the API

Note that if you do modify any control options, you should explicitly enable the control as well by
setting the appropriate Map option value to true. For example, to set a Navigation control to
exhibit the SMALL style, use the following code within Map options object:

  ...
  navigationControl: true,
  navigationControlOptions: {
    style: google.maps.NavigationControlStyle.SMALL
  }
  ...

The following example sets a drop-down MapType control and specifies that the Navigation
control use a small mini-zoom layout:

function initialize() {
  var myOptions = {
    zoom: 4,
    center: new google.maps.LatLng(-33, 151),
    mapTypeControl: true,
    mapTypeControlOptions: {style:
google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    navigationControlOptions: {style:
google.maps.NavigationControlStyle.SMALL},
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                   myOptions);
}



Markers
Markers identify locations on the map. By default, they use a standard icon, though you can set a
custom icon within the marker's constructor or by calling setIcon() on the marker. The
google.maps.Marker constructor takes a single Marker options object literal specifying the
initial properties of the marker. The following fields are particularly important and commonly set
when constructing your marker:

      position (required) specifies a LatLng identifying the initial location of the marker.
      map (optional) specifies the Map object on which to place the marker.

Note that within the Marker constructor, you should specify the map on which to add the marker.
If you do not specify this argument, the marker is created but is not attached (or displayed) on the

                                                                                                34 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
map. You may add the marker later by calling the marker's setMap() method. To remove a
marker, call the setMap() method passing null as the argument.

Markers are designed to be interactive. By default, they receive 'click' events, for example, and
are often used within event listeners to bring up info windows.

The following example adds a simple marker to a map at Uluru, in the center of Australia:

  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title:"Hello World!"
  });

This Marker title will show up as a tooltip.

If you do not wish to pass any Marker options in the marker's constructor, instead pass an empty
object {} in the last argument of the constructor.

Icons

Markers may define an icon to show in place of the default icon. Defining an icon involves setting
a number of properties that define the visual behavior of the marker.

Simple Icons
In the most basic case, an icon can simply indicate an image to use instead of the default Google
Maps pushpin icon by setting the marker's icon property to the URL of an image. The Google
Maps API will size the icon automatically in this case.

In the example below, we create an icon to signify the position of Bondi Beach in Sydney,
Australia:

function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var myOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

                                                                                            35 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    var image = 'beachflag.png';
    var myLatLng = new google.maps.LatLng(-33.890542, 151.274856);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
}

Complex Icons
More complex icons will want to specify complex shapes (which indicate regions that are
clickable), add shadow images, and specify the "stack order" of how they should display relative to
other overlays. Icons specifed in this manner should set their icon and shadow properties to an
object of type MarkerImage.

Shadow images should generally be created at a 45 degree angle (upward and to the right) from the
main image, and the bottom left corner of the shadow image should align with the bottom-left
corner of the icon image. Shadow images should be 24-bit PNG images with alpha transparency so
that image boundaries appear correctly on the map.

MarkerImage     objects not only define an image, but also define the size of the icon, the origin of
the icon (if the image you want is part of a larger image in a sprite, for example), and the anchor
where the icon's hotspot should be located (which is based on the origin).

The following example creates complex markers to signify beaches near Sydney, NSW, Australia.
Note that the anchor is set to (0,32) to correspond to the base of the flagpole.

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

    setMarkers(map, beaches);
}

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var beaches = [
   ['Bondi Beach', -33.890542, 151.274856, 4],
   ['Coogee Beach', -33.923036, 151.259052, 5],
   ['Cronulla Beach', -34.028249, 151.157507, 3],
   ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
   ['Maroubra Beach', -33.950198, 151.259302, 1]
];

                                                                                          36 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
function setMarkers(map, locations) {
  // Add markers to the map

    // Marker sizes are expressed as a Size of X,Y
    // where the origin of the image (0,0) is located
    // in the top left of the image.

    // Origins, anchor positions and coordinates of the marker
    // increase in the X direction to the right and in
    // the Y direction down.
    var image = new google.maps.MarkerImage('images/beachflag.png',
         // This marker is 20 pixels wide by 32 pixels tall.
         new google.maps.Size(20, 32),
         // The origin for this image is 0,0.
         new google.maps.Point(0,0),
         // The anchor for this image is the base of the flagpole at 0,32.
         new google.maps.Point(0, 32));
    var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
         // The shadow image is larger in the horizontal dimension
         // while the position and offset are the same as for the main image.
         new google.maps.Size(37, 32),
         new google.maps.Point(0,0),
         new google.maps.Point(0, 32));
         // Shapes define the clickable region of the icon.
         // The type defines an HTML <area> element 'poly' which
         // traces out a polygon as a series of X,Y points. The final
         // coordinate closes the poly by connecting to the first
         // coordinate.
    var shape = {
         coord: [1, 1, 1, 20, 18, 20, 18 , 1],
         type: 'poly'
    };
    for (var i = 0; i < locations.length; i++) {
       var beach = locations[i];
       var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
       var marker = new google.maps.Marker({
           position: myLatLng,
           map: map,
           shadow: shadow,
           icon: image,
           shape: shape,
           title: beach[0],
           zIndex: beach[3]
       });
    }
}

Polylines

The Polyline class defines a linear overlay of connected line segments on the map. A Polyline
object consists of an array of LatLng locations, and creates a series of line segments that connect
those locations in an ordered sequence.




                                                                                         37 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Polyline Options

The Polyline constructor takes a set of Polyline options specifying the LatLng coordinates of
the line and a set of styles to adjust the polyline's visual behavior.

Polylines  are drawn as a series of straight segments on the map. You can specify custom colors,
weights, and opacities for the stroke of the line within a Polyline options object used when
constructing your line, or change those properties after construction. A polyline supports the
following stroke styles:

       strokeColor specifies a hexadecimal HTML color of the format "#FFFFFF". The Polyline
        class does not support named colors.
       strokeOpacity specifies a numerical fractional value between 0.0 and 1.0 (default) of the
        opacity of the line's color.
       strokeWeight specifies the weight of the line's stroke in pixels.

The following code snippet creates a 2-pixel-wide red polyline connecting the path of William
Kingsford Smith's first trans-Pacific flight between Oakland, CA and Brisbane, Australia:


function initialize() {
  var myLatLng = new google.maps.LatLng(0, -180);
  var myOptions = {
     zoom: 3,
     center: myLatLng,
     mapTypeId: google.maps.MapTypeId.TERRAIN
  };

    var map = new google.maps.Map(document.getElementById("map_canvas"),
         myOptions);
    var flightPlanCoordinates = [
       new google.maps.LatLng(37.772323, -122.214897),
       new google.maps.LatLng(21.291982, -157.821856),
       new google.maps.LatLng(-18.142599, 178.431),
       new google.maps.LatLng(-27.46758, 153.027892)
    ];
    var flightPath = new google.maps.Polyline({
       path: flightPlanCoordinates,
       strokeColor: "#FF0000",
       strokeOpacity: 1.0,
       strokeWeight: 2
    });

    flightPath.setMap(map);
}

Polyline Arrays

A polyline specifies a series of coordinates as an array of LatLng objects. To retrieve these
coordinates, call the Polyline's getPath(), which will return an array of type MVCArray. As such,
you can manipulate and inspect the array using the following operations:

                                                                                          38 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
        getAt() returns the LatLng at a given zero-based index value.
        insertAt() inserts a passed LatLng at a given zero-based index value. Note that any existing
         coordinates at that index value are moved forward.
        removeAt() removes a LatLng at a given zero-based index value.

Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]; you
must use mvcArray.getAt(i).

The following code creates an interactive map which constructs a polyline based on user clicks.
Note that the polyline only appears once its path property contains two LatLng coordinates.


var pathCoordinates = [];
var poly;
var map;

function initialize() {
  var chicago = new google.maps.LatLng(41.879535, -87.624333);
  var myOptions = {
     zoom: 7,
     center: chicago,
     mapTypeId: google.maps.MapTypeId.ROADMAP
  };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    // We create pathCoordinates as an MVCArray so we can
    // manipulate it using the insertAt() method
    pathCoordinates = new google.maps.MVCArray();

    var polyOptions = {
      path: pathCoordinates,
      strokeColor: '#000000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    }
    poly = new google.maps.Polyline(polyOptions);
    poly.setMap(map);

    // Add a listener for the click event
    google.maps.event.addListener(map, 'click', addLatLng);
}

function addLatLng(event) {
  var path = poly.getPath();

    // Because path is an MVCArray, we can simply append a new coordinate
    // and it will automatically appear
    path.insertAt(pathCoordinates.length, event.latLng);

    var marker = new google.maps.Marker({
      position: event.latLng,
      map: map
    });
    marker.setTitle("#" + pathCoordinates.length);
}
                                                                                            39 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Polygons

Polygon   objects are similar to Polyline objects in that they consist of a series of coordinates in an
ordered sequence. However, instead of being open-ended, polygons are designed to define regions
within a closed loop. Similar to polylines, they allow you to define a stroke, which affects the
outline of the polygon; unlike polylines, they also allow you to define a fill region inside the
polygon.

Additionally, Polygons may potentially exhibit complex shapes, including discontinuities
(multiple polygons defined as one polygon), "donuts" (where polygonal areas appear inside the
polygon as "islands") and intersections of one or more polygons. For this reason, a single polygon
may specify multiple paths.




Polygon Options
As with polylines, you can define custom colors, weights, and opacities for the edge of the polygon
(the "stroke") and custom colors and opacities for the area within the enclosed region (the "fill").
Colors should be indicated in hexadecimal numeric HTML style.

Because a polygonal area may include several separate paths, the Polygon object's paths property
specifies an "array of arrays," (each of type MVCArray) where each array defines a separate
sequence of ordered LatLng coordinates.

However, for simple polygons consisting of only one path, you may construct a Polygon using a
single array of LatLng coordinates as a convenience. The Google Maps API will convert this
simple array into an "array of arrays" upon construction when storing it within the Polygon's
paths property. As well, the API provides a simple getPath() methods for simple polygons
consisting of one path.

Note: if you construct a polygon in this manner, you will still need to retrieve values from the
polygon by manipulating the path as an MVCArray.

The following code snippet creates a polygon representing the Bermuda Triangle:


function initialize() {
  var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
  var myOptions = {
     zoom: 5,
     center: myLatLng,
     mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var bermudaTriangle;

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);

                                                                                           40 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    var triangleCoords = [
       new google.maps.LatLng(25.774252,            -80.190262),
       new google.maps.LatLng(18.466465,            -66.118292),
       new google.maps.LatLng(32.321384,            -64.75737),
       new google.maps.LatLng(25.774252,            -80.190262)
    ];

    // Construct the polygon
    // Note that we don't specify an array or arrays, but instead just
    // a simple array of LatLngs in the paths property
    bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35
    });

    bermudaTriangle.setMap(map);
}

Polygon Auto-Completion

The Polygon in the example above consists of four coordinates, but notice that the first and last
coordinate are the same location, which defines the loop. In practice, however, since polygons
define closed areas, you don't need to define this last coordinate. The Maps API will automatically
"close" any polygons by drawing a stroke connecting the last coordinate back to the first
coordinate for any given paths.

The following example is identical to the first example except that the last coordinate is omitted.

Polygon Arrays

A polygon specifies its series of coordinates as an array of arrays, where each array is of type
MVCArray. Each "leaf" array is an array of LatLng coordinates specifying a single path. To retrieve
these coordinates, call the Polygon's getPaths() method. Since the array is an MVCArray you will
need to manipulate and inspect it using the following operations:

        getAt() returns the LatLng at a given zero-based index value.
        insertAt() inserts a passed LatLng at a given zero-based index value. Note that any existing
         coordinates at that index value are moved forward.
        removeAt() removes a LatLng at a given zero-based index value.

Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]; you
must use mvcArray.getAt(i).

The following code handles click events on the polygon by displaying information on the
polygon's coordinates:


                                                                                            41 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
var map;
var infoWindow;

function initialize() {
  var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
  var myOptions = {
     zoom: 5,
     center: myLatLng,
     mapTypeId: google.maps.MapTypeId.TERRAIN
  };

    var bermudaTriangle;

    map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

    var triangleCoords = [
       new google.maps.LatLng(25.774252, -80.190262),
       new google.maps.LatLng(18.466465, -66.118292),
       new google.maps.LatLng(32.321384, -64.75737)
    ];

    bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 3,
      fillColor: "#FF0000",
      fillOpacity: 0.35
    });

    bermudaTriangle.setMap(map);

    // Add a listener for the click event
    google.maps.event.addListener(bermudaTriangle, 'click', showArrays);

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

function showArrays(event) {

    // Since this Polygon only has one path, we can call getPath()
    // to return the MVCArray of LatLngs
    var vertices = this.getPath();

  var contentString = "<b>Bermuda Triangle Polygon</b><br />";
  contentString += "Clicked Location: <br />" + event.latLng.lat() + "," +
event.latLng.lng() + "<br />";

  // Iterate over the vertices.
  for (var i =0; i < vertices.length; i++) {
    var xy = vertices.getAt(i);
    contentString += "<br />" + "Coordinate: " + i + "<br />" + xy.lat() +"," +
xy.lng();
  }

    // Replace our Info Window's content and position

                                                                           42 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    infowindow.setContent(contentString);
    infowindow.setPosition(event.latLng);

    infowindow.open(map);
}

Info Windows

InfoWindows     displays content in a floating window above the map. The info window looks a little
like a comic-book word balloon; it has a content area and a tapered stem, where the tip of the stem
is at a specified location on the map. You can see the info window in action by clicking business
markers on Google Maps.

The InfoWindow constructor takes an InfoWindow options object, which specifies a set of initial
parameters for display of the info window. Upon creation, an info window is not added to the map.
To make the info window visible, you need to call the open() method on the InfoWindow, passing
it the Map on which to open, and optionally, the Marker with which to anchor it. (If no marker is
provided, the info window will open at its position property.)

The InfoWindow options object is an object literal containing the following fields:

       content contains either a string of text or DOM node to display within the info window when it is
        opened.
       pixelOffset contains an offset from the tip of the info window to the location on which the info
        window is anchored. In practice, you should not need to modify this field.
       position contains the LatLng at which this info window is anchored. Note that opening an info
        window on a marker will automatically update this value with a new position.
       maxWidth specifies the maximum width in pixels of the info window. By default, an info window
        expands to fit its content, and auto-wraps text if the info window expands to fill the map. If you
        implement a maxWidth the info window will auto-wrap to enforce the pixel width. Once it
        reaches the maximum width, the info window may still expand vertically if screen real estate is
        available.

The InfoWindow's content may contain either a string of text, a snippet of HTML, or a DOM
element itself. To set this content, either pass it within the InfoWindow options constructor or
call setContent() on the InfoWindow explicitly. If you wish to explicitly size the content, you
may use <div>s to do so, and enable scrolling if you wish. Note that if you do not enable scrolling
and the content exceeds the space available in an info window, the content may "spill" out of the
info window.

InfoWindows    may be attached to either Marker objects (in which case their position is based on
the marker's location) or on the map itself at a specified LatLng. If you only want one info window
to display at a time (as is the behavior on Google Maps), you need only create one info window,
which you can reassign to different locations or markers upon map events (such as user clicks).
Unlike behavior in V2 of the Google Maps API, however, a map may now display multiple
InfoWindow objects if you so choose.




                                                                                              43 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
To change the info window's location you may either change its position explicitly by calling
setPosition() on the info window, or by attaching it to a new marker using the
InfoWindow.open() method. Note that if you call open() without passing a marker, the
InfoWindow will use the position specified upon construction through the InfoWindow options
object.

The following code displays a marker within the center of Australia. Clicking on that marker
shows the info window.

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
  zoom: 4,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
    '<div id="bodyContent">'+
    '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
    'sandstone rock formation in the southern part of the '+
    'Northern Territory, central Australia. It lies 335 km (208 mi) '+
    'south west of the nearest large town, Alice Springs; 450 km '+
    '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
    'features of the Uluru - Kata Tjuta National Park. Uluru is '+
    'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
    'Aboriginal people of the area. It has many springs, waterholes, '+
    'rock caves and ancient paintings. Uluru is listed as a World '+
    'Heritage Site.</p>'+
    '<p>Attribution: Uluru, <a
href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
    'http://en.wikipedia.org/w/index.php?title=Uluru</a> (last visited June 22,
2009).</p>'+
    '</div>'+
    '</div>';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"Uluru (Ayers Rock)"
});

google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map,marker);
});

An example with the info window maxWidth set to 200 pixels appears below:
                                                                                       44 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Custom Overlays

The Google Maps API V3 provides an OverlayView class for creating your own custom overlays.
The OverlayView is a base class providing several methods you must implement when creating
your overlays. The class also provides a few methods that make it possible to translate between
screen coordinates and locations on the map.

To create a custom overlay:

        Set the custom object's prototype to a new instance of google.maps.OverlayView(). This
         will effectively "subclass" the overlay class.
        Create a constructor for your custom overlay, and set any initialization parameters to custom
         properties within that constructor.
        Implement an onAdd() method within your prototype, and attach the overlay to the map.
         OverlayView.onAdd() will be called when the map is ready for the overlay to be attached..
        Implement a draw() method within your prototype, and handle the visual display of your object.
         OverlayView.draw() will be called when the object is first displayed as well.
        You should also implement an onRemove() method to clean up any elements you added within
         the overlay.

We'll step through this explanation below.

SubClassing an Overlay

We'll use OverlayView to create a simple image overlay (similar to the GGroundOverlay within
the V2 API). We'll create a USGSOverlay object which contains a USGS image of the area in
question and the bounds of the image.

var overlay;

function initialize() {
  var myLatLng = new google.maps.LatLng(62.323907, -150.109291);
  var myOptions = {
     zoom: 11,
     center: myLatLng,
     mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

    var swBound = new google.maps.LatLng(62.281819, -150.287132);
    var neBound = new google.maps.LatLng(62.400471, -150.005608);
    var bounds = new google.maps.LatLngBounds(swBound, neBound);

    // Photograph courtesy of the U.S. Geological Survey
    var srcImage = 'images/talkeetna.png';
    overlay = new USGSOverlay(bounds, srcImage, map);
}




                                                                                            45 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Next, we'll create a constructor for this class, and initialize the passed parameters as properties of
the new object. We will also need to explicitly subclass the USGSOverlay from OverlayView. We
do this by setting the new class' prototype to an instance of the parent class. (We set the
prototype here to an instance, rather than the parent class itself, because we do not wish to modify
the parent class.)

function USGSOverlay(bounds, image, map) {

    // Now initialize all properties.
    this.bounds_ = bounds;
    this.image_ = image;
    this.map_ = map;

    // We define a property to hold the image's
    // div. We'll actually create this div
    // upon receipt of the add() method so we'll
    // leave it null for now.
    this.div_ = null;

    // Explicitly call setMap() on this overlay
    this.setMap(map);
}

USGSOverlay.prototype = new google.maps.OverlayView();

We can't yet attach this overlay to the map in the overlay's constructor. In specific, we need to
ensure that all of the map's panes (which specify in what order objects are displayed on a map) are
available. Conveniently, the API provides a helper method indicating this has occurred. We'll
handle that method in the next section.

Initializing an Overlay

When the overlay is first instantiated and ready to display, we'll need to attach it to the map via the
browser's DOM. The API indicates that the overlay has been added to the map by invoking the
overlay's onAdd() method. We'll handle this method by creating a <div> to hold our image, add an
<img> element, attach it to the <div>, and then finally attach the overlay to one of the map's panes,
which are nodes within the DOM tree.

The set of panes, of type MapPanes, specify the stacking order for different layers on the map. The
following panes are possible, and enumerated in the order in which they are stacked from bottom
to top:

        MapPanes.mapPane
        MapPanes.overlayLayer
        MapPanes.overlayShadow
        MapPanes.overlayImage
        MapPanes.floatShadow
        MapPanes.overlayMouseTarget
        MapPanes.floatPane



                                                                                           46 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Because our image is a "ground overlay," we'll use the overlayLayer map pane. Once we have
that pane, we'll attach our object to it as a child.

USGSOverlay.prototype.onAdd = function() {

    // Note: an overlay's receipt of onAdd() indicates that
    // the map's panes are now available for attaching
    // the overlay to the map via the DOM.

    // Create the DIV and set some basic attributes.
    var div = document.createElement('DIV');
    div.style.border = "0px solid none";
    div.style.position = "absolute";

    // Create an IMG element and attach it to the DIV.
    var img = document.createElement("img");
    img.src = this.image_;
    img.style.width = "100%";
    img.style.height = "100%";
    div.appendChild(img);

    // Set the overlay's div_ property to this DIV
    this.div_ = div;

    // We add an overlay to a map via one of the map's panes.
    // We'll add this overlay to the overlayImage pane.
    var panes = this.getPanes();
    panes.overlayImage.appendChild(div);
}

Drawing an Overlay

Note that we haven't actually invoked any special visual display above. The API invokes a separate
draw() method on the overlay whenever it needs to draw the overlay on the map (including when
first added).

We'll therefore implement this draw() method, retrieve the overlay's MapCanvasProjection using
getProjection()and calculate the exact coordinates at which to anchor the object's top right and
bottom left points, from which we'll resize the <div>; in turn this will resize the image to match
the bounds we specified in the overlay's constructor.

USGSOverlay.prototype.draw = function() {

    // Size and position the overlay. We use a southwest and northeast
    // position of the overlay to peg it to the correct position and size.
    // We need to retrieve the projection from this overlay to do this.
    var overlayProjection = this.getProjection();

    // Retrieve the southwest and northeast coordinates of this overlay
    // in latlngs and convert them to pixels coordinates.
    // We'll use these coordinates to resize the DIV.
    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());


                                                                                      47 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    // Resize the image's DIV to fit the indicated dimensions.
    var div = this.div_;
    div.style.left = sw.x + 'px';
    div.style.top = ne.y + 'px';
    div.style.width = (ne.x - sw.x) + 'px';
    div.style.height = (sw.y - ne.y) + 'px';
}

Removing an Overlay

We'll also add an onRemove() method to cleanly remove the overlay from the map. This method
will be called automatically from the API if we ever set the overlay's map property to null.

USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
}




Hiding and Showing an Overlay

If you wish to hide or show an overlay rather than simply create or remove the overlay, you can
implement your own hide() and show() methods to adjust the overlay's visibility. Alternatively,
you may detach the overlay from the map's DOM, though this operation is slightly more
expensive. Note that if you then reattach the overlay to the map's DOM, it will re-invoke the
overlay's onAdd() method.

The following example adds hide() and show() methods to the overlay's prototype which toggle
the container <div>'s visibility. Additionally, we add a toogleDOM() method, which attaches or
detaches the overlay to the map. Note that if we set the visibility to "hidden" and then detach the
map from the DOM via toggleDOM(), if we later reattach the map, it will be visible again, since
the containing <div> is recreated in the overlay's onAdd() method.

// Note that the visibility property must be a string enclosed in quotes
USGSOverlay.prototype.hide = function() {
  if (this.div_) {
    this.div_.style.visibility = "hidden";
  }
}

USGSOverlay.prototype.show = function() {
  if (this.div_) {
    this.div_.style.visibility = "visible";
  }
}

USGSOverlay.prototype.toggle = function() {
  if (this.div_) {
    if (this.div_.style.visibility == "hidden") {
      this.show();
    } else {

                                                                                         48 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
             this.hide();
         }
     }
}

USGSOverlay.prototype.toggleDOM = function() {
  if (this.getMap()) {
    this.setMap(null);
  } else {
    this.setMap(this.map_);
  }
}

// Now we add an input button to initiate the toggle method
// on the specific overlay
<div id ="toolbar" width="100%; height:20px;" style="text-align:center">
  <input type="button" value="Toggle Visibility"
onclick="overlay.toggle();"></input>
  <input type="button" value="Toggle DOM Attachment"
onclick="overlay.toggleDOM();"></input>
</div>
<div id="map_canvas" style="width: 100%; height: 95%;"></div>



Geocoding

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain
View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739),
which you can use to place markers or position the map.

The Google Maps API provides a geocoder class for geocoding addresses dynamically from user
input. If instead, you wish to geocode static, known addresses, see the HTTP Geocoding Service
documentation. (Note that if you wish to use the HTTP service, you will need to sign up for an API
key.)

Geocoding Requests

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a
call to an external server. For that reason, you need to pass a callback method to execute upon
completion of the request. This callback method processes the result(s). Note that the geocoder
may return more than one result.

You access the Google Maps API geocoding service within your code via the
google.maps.Geocoder object. The Geocoder.geocode() method initiates a request to the
geocoding service, passing it a GeocodeRequest object literal containing the input terms and a
callback method to execute upon receipt of the response.

The GeocodeRequest object literal contains the following fields:

{
    address: string,
    latLng: LatLng,
                                                                                       49 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    bounds: LatLngBounds,
    language: string,
    country: string,
}

These fields are explained below.

        address (required) — The address that you want to geocode.*
        latLng (required*) — The LatLng for which you wish to obtain the closest, human-readable
         address.
        bounds (optional) — The LatLngBounds within which to bias geocode results more prominently.
         (For more information see Viewport Biasing below.)
        language (optional) — The language in which to return results.
        region (optional) — The country code, specified as a ccTLD ("top-level domain") two-character
         value. (For more information see Country Code Biasing below.)

* Note: You may pass either an address or a latLng to lookup. (If you pass a latLng, the
geocoder performs what is known as a reverse geocode. See Reverse Geocoding for more
information.)

The bounds and country parameters will only influence, not fully restrict, results from the
geocoder.

Geocoding Responses

The Geocoding service requires a callback method to execute upon retrieval of the geocoder's
results. This callback should pass two parameters to hold the results and a status code, in that
order. Since the Geocoder may return more than one entry, the GeocodeResults object literal is an
array.

Geocoding Results

The GeocodeResults object literal is a JSON object of the following form:

results[]: {
  types[]: google.maps.GeocoderLocationType,
  formatted_address: String,
  address_components[]: {
     short_name: String,
     long_name: String,
     types[]: String
  },
  geometry: {
     location: LatLng,
     location_type: String
     viewport: LatLngBounds,
     bounds: LatLngBounds
  }
}

These fields are explained below:
                                                                                            50 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
      types[]   is an array indicating the type of the returned result. This array contains a set of
       one or more tags identifying the type of feature returned in the result. For example, a
       geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city, and also
       returns "political" which indicates it is a political entity.
      formatted_address is a string containing the human-readable address of this location.
       Often this address is equivalent to the "postal address," which sometimes differs from
       country to country. (Note that some countries, such as Great Britain, do not allow
       distribution of true postal addresses due to licensing restrictions.) This address is generally
       composed of one or more address components. For example, the address "111 8th Avenue,
       New York, NY" contains separate address components for "111 8th Avenue" (a street
       address), "New York" (the city) and "NY" (the US state). These address components are
       noted below. (For more information on types, see Types below.
      address_component[] is an array containing the separate address components, as
       explained above.
      geometry contains the following information:
           o   location contains the geocoded latitude,longitude value. Note that we return this
               location as a LatLng object, not as a formatted string.
           o   location_type stores additional data about the specified location. The following
               values are currently supported:
                      google.maps.GeocoderLocationType.ROOFTOP indicates that the returned
                       result reflects a precise geocode.
                      google.maps.GeocoderLocationType.RANGE_INTERPOLATED indicates
                      that the returned result reflects an approximation (usually on a road) interpolated
                      between two precise points (such as intersections). Interpolated results are
                      generally returned when rooftop geocodes are unavailable for a street address.
                    google.maps.GeocoderLocationType.GEOMETRIC_CENTER indicates that
                      the returned result is the geometric center of a result such as a polyline (for
                      example, a street) or polygon (region).
                    google.maps.GeocoderLocationType.APPROXIMATE indicates that the
                      returned result is approximate.
           o   viewport stores the recommended viewport for the returned result.
           o   bounds (optionally returned) stores the LatLngBounds which can fully contain the
               returned result. Note that these bounds may not match the recommended viewport. (For
               example, San Francisco includes the Farallon islands, which are technically part of the city,
               but should not be returned in the viewport.)

Address Component Types

The types[] array within the returned result indicates the address type. These types may also be
returned within address_components[] arrays to indicate the type of the particular address
component. Addresses within the geocoder may have multiple types; the types may be considered
"tags". For example, many cities are tagged with the political and locality type.

The following types are supported and returned by the HTTP Geocoder:

      street_address indicates a precise street address.
      route indicates a named route (such as "US 101").
      intersection indicates a major intersection, usually of two major roads.
                                                                                               51 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
      political indicates a political entity. Usually, this type indicates a polygon of some civil
       administration.
      country indicates the national political entity, and is typically the highest order type returned by
       the Geocoder.
      administrative_area_level_1 indicates a first-order civil entity below the country level.
       Within the United States, these administrative levels are states. Not all nations exhibit these
       administrative levels.
      administrative_area_level_2 indicates a second-order civil entity below the country level.
       Within the United States, these administrative levels are counties. Not all nations exhibit these
       administrative levels.
      administrative_area_level_3 indicates a third-order civil entity below the country level.
       This type indicates a minor civil division. Not all nations exhibit these administrative levels.
      colloquial_area indicates a commonly-used alternative name for the entity.
      locality indicates an incorporated city or town political entity.
      sublocality indicates an first-order civil entity below a locality
      neighborhood indicates a named neighborhood
      premise indicates a named location, usually a building or collection of buildings with a common
       name
      subpremise indicates a first-order entity below a named location, usually a singular building
       within a collection of buildings with a common name
      postal_code indicates a postal code as used to address postal mail within the country.
      natural_feature indicates a prominent natural feature.
      airport indicates an airport.
      park indicates a named park.

In addition to the above, address components may exhibit the following types:

      post_box indicates a specific postal box.
      street_number indicates the precise street number.
      floor indicates the floor of a building address.
      room indicates the room of a building address.

Status Codes

The status code may return one of the following values:

      google.maps.GeocoderStatus.OK indicates that the geocode was successful.
      google.maps.GeocoderStatus.ZERO_RESULTS indicates that the geocode was successful but
       returned no results. This may occur if the geocode was passed a non-existent address or a
       latng in a remote location.
      google.maps.GeocoderStatus.OVER_QUERY_LIMIT indicates that you are over your quota.
      google.maps.GeocoderStatus.REQUEST_DENIED indicates that your request was denied for
       some reason.
      google.maps.GeocoderStatus.INVALID_REQUEST generally indicates that the query
       (address or latLng) is missing.

In this example, we geocode an address and place a marker at the returned latitude and longitude
values. Note that the handler is passed as an anonymous function literal.

                                                                                                52 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  var geocoder;
  var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
           map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
               map: map,
               position: results[0].geometry.location
           });
         } else {
           alert("Geocode was not successful for the following reason: " +
status);
         }
      });
    }
  }

<body onload="initialize()">
 <div id="map_canvas" style="width: 320px; height: 480px;"></div>
  <div>
    <input id="address" type="textbox" value="Sydney, NSW">
    <input type="button" value="Encode" onclick="codeAddress()">
  </div>
</body>

Reverse Geocoding (Address Lookup)
The term geocoding generally refers to translating a human-readable address into a location on a
map. The process of doing the converse, translating a location on the map into a human-readable
address, is known as reverse geocoding.

The Geocoder supports reverse geocoding directly. Instead of supplying a textual address, supply
a comma-separated latitude/longitude pair in the latLng parameter.

The following example geocodes a latitude/longitude value and centers the map at that location,
bringing up an info window with the formatted address. We return the second result, which is less
specific than the first (in this case, a neighborhood name):

  var geocoder;
  var map;
                                                                                       53 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  var infowindow = new google.maps.InfoWindow();
  var marker;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
  }

  function codeLatLng() {
    var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = latlngStr[0];
    var lng = latlngStr[1];
    var latlng = new google.maps.LatLng(lat, lng);
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(11);
            marker = new google.maps.Marker({
                 position: latlng,
                 map: map
            });
            infowindow.setContent(results[1].formatted_address);
            infowindow.open(map, marker);
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

Note that in the previous example we showed the second result (by selecting results[1]. The
reverse geocoder often returns more than one result. Geocoding "addresses" are not just postal
addresses, but any way to geographically name a location. For example, when geocoding a point in
the city of Chicago, the geocoded point may be labeled as a street address, as the city (Chicago), as
its state (Illinois) or as a country (The United States). All are addresses to the geocoder. The
reverse geocoder returns all of these results.

The reverse geocoder matches political entities (countries, provinces, cities and neighborhoods),
street addresses, and postal codes.

The full list of addresses returned by the previous query are shown below.

results[0].formatted_address:          "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
results[1].formatted_address:          "Williamsburg, NY, USA",
results[2].formatted_address:          "New York 11211, USA",
results[3].formatted_address:          "Kings, New York, USA",

                                                                                         54 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
results[4].formatted_address:          "Brooklyn, New York, USA",
results[5].formatted_address:          "New York, New York, USA",
results[6].formatted_address:          "New York, USA",
results[7].formatted_address:          "United States"

Addresses are returned in the order of best to least matches. Generally, the more exact address is
the most prominent result, as it is in this case. Note that we return different types of addresses,
from the most specific street address to less specific political entities such as neighborhoods, cities,
counties, states, etc. If you wish to match a more general address, you may wish to inspect the
results[].types field.

Note: Reverse geocoding is not an exact science. The geocoder will attempt to find the closest
addressable location within a certain tolerance.

Viewport Biasing

You can also instruct the Geocoding Service to prefer results within a given viewport (expressed as
a bounding box). You do so by setting the bounds parameter within the GeocodeRequest object
literal to define the bounds of this viewport.

For example, a geocode for "Winnetka" generally returns this suburb of Chicago:

{
    "types":["locality","political"],
    "formatted_address":"Winnetka, IL, USA",
    "address_components":[{
      "long_name":"Winnetka",
      "short_name":"Winnetka",
      "types":["locality","political"]
    },{
      "long_name":"Illinois",
      "short_name":"IL",
      "types":["administrative_area_level_1","political"]
    },{
      "long_name":"United States",
      "short_name":"US",
      "types":["country","political"]
    }],
    "geometry":{
      "location":[ -87.7417070, 42.1083080],
      "location_type":"APPROXIMATE"
    }
}

However, specifying a bounds parameter defining a bounding box for the San Fernando Valley of
Los Angeles results in this geocode returning the neighborhood named "Winnetka" in that
location:

{
    "types":["sublocality","political"],
    "formatted_address":"Winnetka, California, USA",
    "address_components":[{
      "long_name":"Winnetka",
                                                                                            55 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
      "short_name":"Winnetka",
      "types":["sublocality","political"]
    },{
      "long_name":"Los Angeles",
      "short_name":"Los Angeles",
      "types":["administrative_area_level_3","political"]
    },{
      "long_name":"Los Angeles",
      "short_name":"Los Angeles",
      "types":["administrative_area_level_2","political"]
    },{
      "long_name":"California",
      "short_name":"CA",
      "types":["administrative_area_level_1","political"]
    },{
      "long_name":"United States",
      "short_name":"US",
      "types":["country","political"]
    }],
    "geometry":{
      "location": [34.213171,-118.571022],
      "location_type":"APPROXIMATE"
    }
}

Country Code Biasing
The Google Maps API Geocoding Service returns address results influenced by the domain
(country) from which the request is sent. For example, searches for "San Francisco" may return
different results if sent from a domain within the United States than one sent from Spain.

You can also set the Geocoding Service to return results biased to a particular country using the
region parameter. This parameter takes a ccTLD (county code top-level domain) argument
specifying the country bias. Most ccTLD codes are identical to ISO 3166-1 codes, with some
notable exceptions. For example, Great Britain's ccTLD is "uk" (.co.uk) while its ISO 3166-1
code is "GB."

Geocoding requests can be sent for every domain in which the main Google Maps application
offers geocoding.

For example, a geocode for "Toldeo" returns this result, as the default domain for the Geocoding
Service is set to the United States:

{
    "types":["locality","political"],
    "formatted_address":"Toledo, OH, USA",
    "address_components":[{
      "long_name":"Toledo",
      "short_name":"Toledo",
      "types":["locality","political"]
    },{
      "long_name":"Ohio",
      "short_name":"OH",
      "types":["administrative_area_level_1","political"]
                                                                                         56 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    },{
       "long_name":"United States",
       "short_name":"US",
       "types":["country","political"]
    }]
}

A geocode for "Toledo" with the region field set to 'es' (Spain) will return the Spanish city:

{
    "types":["locality","political"],
    "formatted_address":"Toledo, España",
    "address_components":[{
       "long_name":"Toledo",
       "short_name":"Toledo",
       "types":["locality","political"]
    },{
       "long_name":"Toledo",
       "short_name":"TO",
       "types":["administrative_area_level_2","political"]
    },{
       "long_name":"Castilla-La Mancha",
       "short_name":"CM",
       "types":["administrative_area_level_1","political"]
    },{
       "long_name":"España",
       "short_name":"ES",
       "types":["country","political"]
    }]
}

Directions
You can calculate directions (using a variety of methods of transportation) by using the
DirectionsService object. This object communicates with the Google Maps API Directions
Service which receives direction requests and returns computed results. You may either handle
these directions results yourself or use the DirectionsRenderer object to render these results.

Directions may specify origins and destinations either as text strings (e.g. "Chicago, IL" or
"Darwin, NSW, Australia") or as LatLng values. The Directions service can return multi-part
directions using a series of waypoints. Directions are displayed as a polyline drawing the route on
a map, or additionally as a series of textual description within a <div> element (e.g. "Turn right
onto the Williamsburg Bridge ramp").

Directions Requests
Accessing the Directions service is asynchronous, since the Google Maps API needs to make a call
to an external server. For that reason, you need to pass a callback method to execute upon
completion of the request. This callback method should process the result(s). Note that the
Directions service may return more than one possible itinerary as an array of trips[].


                                                                                         57 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
To use directions in V3, create an object of type DirectionsService and call
DirectionsService.route() to initiate a request to the Directions service, passing it a
DirectionsRequest object literal containing the input terms and a callback method to execute
upon receipt of the response.

The DirectionsRequest object literal contains the following fields:

{
    origin: LatLng | String,
    destination: LatLng | String,
    travelMode: DirectionsTravelMode,
    unitSystem: DirectionsUnitSystem,
    waypoints[]: DirectionsWaypoint,
    provideTripAlternatives: Boolean,
    region: String
}

These fields are explained below:

       origin (required) specifies the start location from which to calculate directions. This value may
        either be specified as a String (e.g. "Chicago, IL") or as a LatLng value.
       destination (required) specifies the end location to which to calculate directions. This value
        may either be specified as a String (e.g. "Chicago, IL") or as a LatLng value.
       travelMode (required) specifies what mode of transport to use when calculating directions. Valid
        values are specified in Travel Modes below.
       unitSystem     (optional) specifies what unit system to use when displaying results. Valid
        values are specified in Unit Systems below.
       waypoints[] (optional) specifies an array of DirectionsWaypoints. Waypoints alter a
        route by routing it through the specified location(s). A waypoint is specified as an object
        literal with fields shown below:
            o   location specifies the location of the waypoint, either as a LatLng or as a String
                which will be geocoded.
            o   stopover is a boolean which indicates that the waypoint is a stop on the route, which
                has the effect of splitting the route into two routes.

        (For more information on waypoints, see Using Waypoints in Trips below.)

       provideTripAlternatives (optional) when set to true specifies that the Directions service
        may provide more than one trip alternative in the response. Note that providing trip alternatives
        may increase the response time from the server.
       region (optional) specifies the country code, specified as a ccTLD ("top-level domain") two-
        character value. (For more information see Region Biasing below.)

A sample DirectionsRequest is shown below:

{
    origin: "Chicago, IL",
    destination: "Los Angeles, CA",
    waypoints: [
      {

                                                                                              58 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
        location:"Joplin, MO",
        stopover:false
      },{
        location:"Oklahoma City, OK",
        stopover:true
      }],
    provideTripAlternatives: false,
    travelMode: DirectionsTravelMode.DRIVING,
    unitSystem: DirectionsUnitSystem.IMPERIAL
}

Travel Modes

When you calculate directions, you need to specify which transportation mode to use. The
following travel modes are currently supported:

       DirectionsTravelMode.DRIVING indicates standard driving directions using the road
        network.
       DirectionsTravelMode.WALKING requests walking directions via pedestrian paths &
        sidewalks (where available).

Note: Walking directions may sometimes not include clear pedestrian paths, so walking directions
will return warnings in the DirectionsResult which you must display if you are not using the
default DirectionsRenderer.

Unit Systems

By default, directions are calculated and displayed using the unit system of the origin's country.
For example, a route from "Chicago, IL" to "Toronto, ONT" will display results in miles, while the
reverse route will display results in kilometers. You may override this unit system by setting one
explicitly within the request using one of the following DirectionsUnitSystem values:

       DirectionsUnitSystem.METRIC specifies usage of the metric system. Distances are shown
        using kilometers.
       DirectionsUnitSystem.IMPERIAL specifies usage of the Imperial (English) system. Distances
        are shown using miles.

Note: this unit system setting only affects the text displayed to the user. The directions result also
contains distance values, not shown to the user, which are always expressed in meters.

Region Biasing

The Google Maps API Directions Service returns address results influenced by the domain
(country) from which the request is sent. For example, direction queries for "San Francisco" may
return different results if sent from a domain within the United States than one sent from Spain.

You can also set the Directions service to return results biased to a particular country using the
region parameter. This parameter takes a ccTLD (county code top-level domain) argument
specifying the country bias. Most ccTLD codes are identical to ISO 3166-1 codes, with some

                                                                                            59 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
notable exceptions. For example, Great Britain's ccTLD is "uk" (.co.uk) while its ISO 3166-1
code is "GB."

Consult the Google Maps coverage spreadsheet to determine to what extent a country supports
directions.

Rendering Directions

Initiating a directions request to the DirectionsService with the route() method requires
passing a callback which executes upon completion of the service request. This callback will return
a DirectionsResult and a DirectionsStatus code in the response.

Status of Directions Query

The DirectionsStatus may return the following values:

      OK indicates the response contains a valid DirectionsResult.
      NOT_FOUND indicates at least one of the locations specified in the requests's origin, destination, or
       waypoints could not be geocoded.
      ZERO_RESULTS indicates no route could be found between the origin and destination.
      MAX_WAYPOINTS_EXCEEDED indicates that too many DirectionsWaypoints were provided in
       the DirectionsRequest. The maximum allowed waypoints is 23, plus the origin, and
       destination.
      INVALID_REQUEST indicates that the provided DirectionsRequest was invalid.
      OVER_QUERY_LIMIT indicates the webpage has sent too many requests within the allowed time
       period.
      REQUEST_DENIED indicates the webpage is not allowed to use the directions service.
      UNKNOWN_ERROR indicates a directions request could not be processed due to a server error. The
       request may succeed if you try again.

You should ensure that the directions query returned valid results by checking this value before
processing the result.

Displaying the DirectionsResult

The DirectionsResult contains the result of the directions query, which you may either handle
yourself, or pass to a DirectionsRenderer object, which can automatically handle displaying the
result on a map.

To display a DirectionsResult using a DirectionsRenderer, you simply need to do the
following:

   1. Create a DirectionsRenderer object.
   2. Call setMap() on the renderer to bind it to the passed map.
   3. Call setDirections() on the renderer, passing it the DirectionsResult as noted above.
      Because the renderer is an MVCObject, it will automatically detect any changes to its properties
      and update the map when its associated directions have changed.

                                                                                               60 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
The following example calculates directions between two locations on Route 66, where the origin
and destination are set by the given "start" and "end" values in the dropdown lists. The
DirectionsRenderer handles display of the polyline between the indicated locations, and the
placement of markers at the origin, destination, and any waypoints, if applicable.

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
     origin:start,
     destination:end,
     travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
     if (status == google.maps.DirectionsStatus.OK) {
       directionsDisplay.setDirections(result);
     }
  });
}

<div>
<b>Start: </b>
<select id="start" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
<b>End: </b>
<select id="end" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>

                                                                                     61 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  <option    value="oklahoma city, ok">Oklahoma City</option>
  <option    value="amarillo, tx">Amarillo</option>
  <option    value="gallup, nm">Gallup, NM</option>
  <option    value="flagstaff, az">Flagstaff, AZ</option>
  <option    value="winona, az">Winona</option>
  <option    value="kingman, az">Kingman</option>
  <option    value="barstow, ca">Barstow</option>
  <option    value="san bernardino, ca">San Bernardino</option>
  <option    value="los angeles, ca">Los Angeles</option>
</select>
</div>

A DirectionsRenderer not only handles display of the polyline and any associated markers, but
also can handle the textual display of directions as a series of steps. To do so, simply call
setPanel() on your DirectionsRenderer, passing it the <div> in which to display this
information. Doing so also ensures that you display the appropriate copyright information, and any
warnings which may be associated with the result.

Textual directions will be provided using the browser's preferred language setting, or the language
specified when loading the API JavaScript using the language parameter. (For more information,
see Localization.)

The following example is identical to that shown above, but includes a <div> panel in which to
display directions:

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}

function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
     origin:start,
     destination:end,
     travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
     if (status == google.maps.DirectionsStatus.OK) {
       directionsDisplay.setDirections(response);
     }
  });
                                                                                        62 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
}

// select UI elements omitted
<div><div id="map_canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%"></div>

The Directions Results Object

When sending a directions request to the DirectionsService, you receive a response consisting
of a status code, and a result, which is a DirectionsResult object. The DirectionsResult is an
object literal with a single field:

       trips[] contains an array of DirectionsTrip objects. Each trip indicates a way to get from the
        origin to the destination provided in the DirectionsRequest. Generally, only one trip is
        returned for any given request, unless the request's provideTripAlternatives field is set to
        true, in which, multiple trips may be returned.

Directions Trips

A DirectionsTrip contains a single result from the specified origin and destination. This trip may
consist of one or more routes (of type DirectionsRoute) depending on whether any waypoints
were specified. As well, the trip also contains copyright and warning information which must be
displayed to the user in addition to the routing information.

The DirectionsTrip is an object literal with the following fields:

       routes[] contains an array of DirectionsRoute objects, each of which contains information
        about a route from two locations within the given trip. A separate route will be present for each
        waypoint or destination specified. (A trip with no waypoints will contain exactly one
        DirectionsRoute.) Each route consists of a series of DirectionSteps.
       copyrights contains the copyrights text to be displayed for this trip. If you do not use the
        provided DirectionsRenderer object, you must handle and display this information yourself.
       warnings[] contains an array of warnings to be displayed when showing these directions. If you
        do not use the provided DirectionsRenderer object, you must handle and display these
        warnings yourself.

Directions Routes

A DirectionsRoute defines a single leg of a journey from the origin to the destination in the
calculated route. For trips that contain no waypoints, the trip will consist of a single "route," but
for trips that define one or more waypoints, the trip will consist of one or more routes,
corresponding to the specific leg of the journey.

The DirectionsRoute is an object literal with the following fields:

       steps[] contains an array of DirectionsStep objects denoting information about each
        separate step of the route.


                                                                                             63 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
      distance   indicates the total distance covered by this route, as a DirectionsDistance
       object of the following form:
           o   value indicates the distance in meters
           o   text contains a string representation of the distance, which by default is displayed in
               units as used at the origin. (For example, miles will be used for any origin within the
               United States.) You may override this unit system by specifically setting a
               DirectionsUnitSystem in the original query. Note that regardless of what unit system
               you use, the distance.value field always contains a value expressed in meters.

       These fields may be undefined if the distance is unknown.

      duration  indicates the total duration of this route, as a DirectionsDuration object of the
       following form:
           o   value indicates the duration in seconds.
           o   text contains a string representation of the duration.

       These fields may be undefined if the duration is unknown.

      start_geocode contains a GeocoderResponse denoting the precise geocode of the given
       origin. Because the DirectionsService calculates directions between locations by using the
       nearest transportation option (usually a road) at the start and end points, start_geocode
       indicates the actual geocoded origin, which may be different than the first step if, for example, the
       road is not near the origin.
      end_geocode contains a GeocoderResponse denoting the precise geocode of the given
       destination. Because the DirectionsService calculates directions between locations by using
       the nearest transportation option (usually a road) at the start and end points, end_geocode
       indicates the actual geocoded destination, which may be different than the last step if, for
       example, the road is not near the destination.

Directions Steps

A DirectionsStep is the most atomic unit of a direction's trip, containing a single step describing
a specific, single instruction on the journey. E.g. "Turn left at W. 4th St." The step not only
describes the instruction but also contains distance and duration information relating to how this
step relates to the following step. For example, a step denoted as "Merge onto I-80 West" may
contain a duration of "37 miles" and "40 minutes," indicating that the next step is 37 miles/40
minutes from this step.

The DirectionsStep is an object literal with the following fields:

      instructions contains instructions for this step within a text string.
      distance contains the distance covered by this step until the next step, as a
       DirectionsDistance object. (See the description in DirectionsRoute above.) This field may
       be undefined if the distance is unknown.
      duration contains the typical time required to perform the step, until the next step, as a
       DirectionsDuration object. (See the description in DirectionsRoute above.) This field may
       be undefined if the duration is unknown.
      start_point contains the LatLng of the starting point of this step.

                                                                                               64 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
          end_point contains the LatLng of the ending point of this step.


Inspecting DirectionsResults

The DirectionsResults components — DirectionsTrip, DirectionsRoute and
DirectionsStep — may be inspected and used when parsing any directions response.

The following example plots walking directions to certain tourist attractions in New York City. We
inspect the route's DirectionsStep to add markers for each step, and attach information to an
InfoWindow with instructional text for that step.

Note: since we are calculating walking directions, we also display any warnings to the user in a
separate <div> panel.

var       map;
var       directionDisplay;
var       directionsService;
var       stepDisplay;
var       markerArray = [];

function initialize() {
  // Instantiate a directions service.
  directionsService = new google.maps.DirectionsService();

    // Create a map and center it on Manhattan.
    var manhattan = new google.maps.LatLng(40.7711329, -73.9741874);
    var myOptions = {
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: manhattan
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    // Create a renderer for directions and bind it to the map.
    var rendererOptions = {
      map: map
    }
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)

    // Instantiate an info window to hold step text.
    stepDisplay = new google.maps.InfoWindow();
}

function calcRoute() {

    // First, clear out any existing markerArray
    // from previous calculations.
    for (i = 0; i < markerArray.length; i++) {
      markerArray[i].setMap(null);
    }

    // Retrieve the start and end locations and create
    // a DirectionsRequest using WALKING directions.
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
                                                                                        65 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };

    // Route the directions and pass the response to a
    // function to create markers for each step.
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        var warnings = document.getElementById("warnings_panel");
        warnings.innerHTML = "" + response.trips[0].warnings + "";
        directionsDisplay.setDirections(response);
        showSteps(response);
      }
    });
}

function showSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  var myRoute = directionResult.trips[0].routes[0];

    for (var i = 0; i < myRoute.steps.length; i++) {
        var marker = new google.maps.Marker({
          position: myRoute.steps[i].start_point,
          map: map
        });
        attachInstructionText(marker, myRoute.steps[i].instructions);
        markerArray[i] = marker;
    }
}

function attachInstructionText(marker, text) {
  google.maps.event.addListener(marker, 'click', function() {
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

<div>
<b>Start: </b>
<select id="start">
  <option value="penn station, new york, ny">Penn Station</option>
  <option value="grand central station, new york, ny">Grand Central
Station</option>
  <option value="625 8th Avenue New York NY 10018">Port Authority Bus
Terminal</option>
  <option value="staten island ferry terminal, new york, ny">Staten Island
Ferry Terminal</option>
  <option value="101 E 125th Street, New York, NY">Harlem - 125th St
Station</option>
</select>
<b>End: </b>
<select id="end" onchange="calcRoute();">
  <option value="260 Broadway New York NY 10007">City Hall</option>

                                                                        66 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  <option value="W 49th St & 5th Ave, New York, NY 10020">Rockefeller
Center</option>
  <option value="moma, New York, NY">MOMA</option>
  <option value="350 5th Ave, New York, NY, 10118">Empire State
Building</option>
  <option value="253 West 125th Street, New York, NY">Apollo Theatre</option>
  <option value="1 Wall St, New York, NY">Wall St</option>
</select>
<div>

Using Waypoints in Trips
As noted within the DirectionsRequest, you may also specify waypoints (of type
DirectionsWaypoint) when calculating trips using the Directions service. Waypoints allow you
to calculate trips through additional locations, in which case the returned trip passes through the
given waypoints in their provided order.

The following example calculates cross-country trips across the United States using a variety of
start points, end points, and waypoints. (To select multiple waypoints, press Ctrl-Click when
selecting items within the list.) Note that we inspect the
routes.start_geocode.formatted_address and routes.end_geocode.formatted_address
to provide us with the text for each route's start and end point.

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var waypts = [];
  var checkboxArray = document.getElementById("waypoints");
  for (var i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected == true) {
      waypts.push({location:checkboxArray[i].value});
    }
  }

  var request = {
      origin: start,
      destination: end,
      waypoints: waypts,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
                                                                                         67 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
  };
  directionsService.route(request, function(response, status) {
     if (status == google.maps.DirectionsStatus.OK) {
       directionsDisplay.setDirections(response);
       var trip = response.trips[0];
       var summaryPanel = document.getElementById("directions_panel");
       summaryPanel.innerHTML = "";
       // For each route, display summary information.
       for (var i = 0; i < trip.routes.length; i++) {
         var tripSegment = i+1;
         summaryPanel.innerHTML += "<b>Trip Segment: " + tripSegment + "</b><br
/>";
         summaryPanel.innerHTML +=
trip.routes[i].start_geocode.formatted_address + " to ";
         summaryPanel.innerHTML += trip.routes[i].end_geocode.formatted_address
+ "<br />";
         summaryPanel.innerHTML += trip.routes[i].distance.text + "<br /><br
/>";
       }
     }
  });
}




                                                                       68 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Adding a ProgressBar to Google Maps

We‘ll continue our discussion of the ProgressbarControl Google Maps Utility class for enhancing
your users‘ experience during long running operations. This time we‘ll examine the
ProgressbarControl in more detail by reviewing a sample application.

Click here to see the demonstration and click the ‗Add Destroyed Homes‘ button to add the
markers to the map and watch the ProgressbarControl update as the markers are added. We‘ll
discuss the code used to create the ProgressbarControl below the image. You can view the code
used to generate this simple demonstration by right clicking the web page and selecting View Page
Source.




We will be loading the contents of an xml file containing approximately 200 residences destroyed
in the San Diego Witch Fire. Each address in the file is loaded as a marker on the map. Because
this is a large number of markers to add to a map it makes sense to use a ProgressbarControl that
updates your user with the current status of the operation.

The initialize( ) function, as seen below, creates the basic structure of the map including map types
and controls and at the end of this function makes a call to the loadFiresIntoMemory() function.
This function opens the WitchFireResidenceDestroyed.xml file, loops through each record creating
a marker for each address, and finally placing the marker into an array variable called ‗batch‘. We
will use the ‗batch‘ variable later in our code to access each marker and add it to the map. All of
this takes place as the map initially loads.
                                                                                         69 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
We can get away with loading the markers into memory because there are only 230 rows in the
file, but this would not be a good idea if you have a really large dataset due to the performance hit
of loading a large number of records.

Before we can access the ProgressbarControl we need to reference the progressbarcontrol.js file as
seen below. This is done near the top of the file.



Now that we have a reference to progressbarcontrol.js we can create a new instance of
ProgressbarControl. We add the following line of code to the initialize() function just below the
call to loadFiresIntoMemory().




The initialize function should appear as follows:




                                                                                          70 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
Toward the bottom of the file you will see a button called ‗Add Destroyed Homes‘. The ‗onclick‘
event for this button will call a JavaScript function called ‗loadProgressBar()‘. We are going to
create this function next.




Next, we create the loadProgressBar() function that will be called when the ‗Add Destroyed
Homes‘ button is clicked.




Inside the loadProgressBar() function we initialize the ProgressbarControl using the start() method
as seen above. The ProgressbarControl.start() method is used to display the progress bar on the
map. In addition, we pass in a numeric value that defines the maximum value for the bar. In this
case we are getting the size of our array using the length property. Remember that the ‗batch‘
variable is an array containing GMarkers for each address in the xml file.

Next, we use the array.length method again to set a variable called ‗maxNum‘ which will be used
as a counter in a function we will create later.

Finally, we call the setTimeout() JavaScript function. This function is used to set a timer. Since
the browser will not update the screen unless it has time to do so, we use setTimeout with a 1
millisecond delay in between each update. The setTimeout() function also accepts a function


                                                                                         71 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]
reference which will be called after the delay. In this case, the addMarkers() function will be
called after the delay. We‘ll discuss this function next.

Near the top of addMarkers() we called the ProgressbarControl.updateLoader() method which will
update the progress of the control by a value of 1. Next, we pull the next GMarker out of the
‗batch‘ array and add it to the map with GMap2.addOverlay. Finally, we check the value of ‗num‘
to see if it is less than ‗maxNum‘. Remember that ‗maxNum‘ is set to the total number of
GMarker objects loaded in the ‗batch‘ array. This number should be 230. The ‗num‘ value gets
updated each time the ‗addMarkers()‘ function is called until it is less than or equal to ‗maxNum‘.




                                                                                         72 | P a g e
Sanjay Manju Suman [Efextra eSolutions Pvt. Ltd.]

								
To top