142
Introduction to Programming the Google Maps API E-Learning for the GIS Professional Any Time, Any Place! geospatialtraining.com

Introduction to Programming the Google Maps APIs3.amazonaws.com/VirtualGISClassroom/Introduction to the Google Maps... · Basic Google Map - Code •Click here to see a demonstration

  • Upload
    others

  • View
    20

  • Download
    0

Embed Size (px)

Citation preview

Introduction to Programming the Google Maps APIE-Learning for the GIS Professional – Any Time, Any Place!

geospatialtraining.com

Course Modules

• Module 1: Introduction to Programming the Google Maps API

• Module 2: Basic Concepts of the Google Maps API

– Adding Controls to the Map (Zoom, Pan, Map Types, Overview Map, Scale Bar)

– Creating Overlays (Markers, Polylines, Polygons)

– Display Images with Ground Overlays

– Creating Layers (KML, GeoRSS, FusionTables, Bicycling)

• Module 3: Handling Events

• Module 4: Geocoding with Google Maps API

– Geocoding

– Reverse Geocoding

• Module 5: The Google Elevation Service

2

Module 1: Introduction to Programming the Google Maps API

E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com

Google Maps Capabilities

• Create Maps

• Add markers representing points

• Attach info windows to markers

• Create polylines and polygons

• Map data from XML, KML, or database sources

• Change map types

– Aerial, Terrain, Hybrid, Map

• Overlay custom data sources

• View street view images of current location

• Perform map navigation

4

Free for Non-Commercial Uses

Pay

• Intranet

• Commercial

Free

• Internet

• Non-Commercial

Google Maps Premier

Google Maps API

5

Google Maps Premier

• Allows you to develop custom mapping applications for intranet applications

and paid subscription sites

• Requires annual license fee

• Designed for

– Greater capacity for service requests such as geocoding

– The ability to provide secure maps over https

– Business-friendly terms and conditions

– Support and service options

– Control over advertisements within the maps

6

Google Maps API Versions

• Version 3 is current

• 2 Types of versions

– Nightly (development)

• Simply omit the ‘v’ parameter to default to this version

• Or you can use ‘v=3’

– Numbered

• Indicated by ‘v=3.x’ where x is a number

• May be release version or frozen version

8

Release or Frozen Version?

• Each quarter of the year a new numbered version is released

– Called “release” version

– 3.4 as of March 2011

– During this quarter bug fixes will continue to be added to this version

• When a new version is released the previous version is “frozen”

– No further updates or code changes including bug fixes

– The previously existing “frozen” version is then retired

– Only one “frozen” version at a time

– Automatically get the current “frozen” version if an older version is requested

9

Google Maps API Versions Illustrated

Release Version3.4

Frozen Version

3.3

Retired Version

3.2

10

Choosing a Version

• Some general guidelines

– Production applications should use a minor version (3.2., 3.3, etc)

– New applications should be developed with the release or nightly version

• Use until you need to add additional features in a later version

• Version matures as your application develops

11

Browser Compatibility

• Google Maps v3 is not compatible with all browsers

• Current support for

– IE 7.0+ (Windows)

– Firefox 3.0+ (Windows|Mac OS X|Linux)

– Safari 4+ (Mac OS X|iOS)

– Chrome (Windows|Mac OS X|Linux)

– Android

– BlackBerry 6

– Dolfin 2.0+ (Samsung Bada)

• Use GBrowserIsCompatible() to check

– If this method returns false you should redirect the user to an error page

12

Google Maps Documentation

• Documentation can be accessed here.http://code.google.com/apis/maps/documentation/javascript/

– Includes

• Introduction to Google Maps

• API documentation (class, methods, events)

• Code examples

• Demos

• Articles and Presentation

• Google also provides a blog (http://googlegeodevelopers.blogspot.com//) and discussion group (http://code.google.com/apis/maps/documentation/javascript/forum.html) for additional information on using the API.

13

Module 2: Basic Concepts of the Google Maps API

E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com

Module Outline

• Creating a Map

• Adding Controls to the Map

– MapType, Zoom, Pan, Overview Map, ScaleBar, StreetView

• Adding Overlays to the Map

– Markers, Polylines, Polygons, GroundOverlays

• Creating Map Layers

– KML, GeoRSS, Fusion Tables, Traffic, Bicycle

15

Creating a Map

16

Map Creation Steps

17

1. Load the Google Maps API

2. Create a Container for the Map

– Inside a web page

– Usually a <div> tag

3. Define Map Options and Create Map Object

4. Load the Map with Initialization Function

Loading the Google Maps API

• Google Maps API referenced inside a <script> tag

• Points to the source

– http://maps.google.com/maps/api/js?sensor=<true or false>

18

Sensor Parameter

• Sensor parameter set to ‘true’ or ‘false’

– Required parameter!

• Indicates if current location of the application should be found

• Important for mobile applications

19

Geolocation

• Current location of device

• W3C Geolocation

– Part of HTML5

• Use navigator.geolocation

20

Map Container

• Map placed inside a container

– <div> element

• Always give the container an id

• Need to size the map using style attributes

– Map takes its size from the containing element (<div>)

– Use width and height style attributes

21

Map Options

• Need to define various options for the map

• Provide several options at a minimum

– Map center

– Map type

• No default map type

– Zoom level

• Passed to the Map on creation

• Code example on next slide

22

Map

Map Type

Map Level

Map Center

Map Options Code Example

• Map options defined inside a JavaScript object literal

– Set of key value pairs enclosed by curly braces

– Click here to see an illustration (display the png file)

23

Map Options – Centering the Map

• Use google.maps.LatLng object to define the center of the map

• Takes a latitude, longitude coordinate pair

24

Points in Google Maps

Markers

Position Map

PointsLatLng

30.4622, -96.3552

LatLng Object

• A point on the surface of the earth

– Latitude, longitude coordinate pair

• Has many uses in the Google Maps API

– Centering the map

– Creating markers, polylines, and polygons

– Defining the location where an InfoWindow will be displayed

• Creating a LatLng object

26

Map Options – Zoom Level

• The map resolution is defined by the zoom level

• Can be a value between 0 and 18

– 0 = Fully zoomed out

– 18 = Fully zoomed in

27

Map Options – Map Type

• No default map type; must be set

• Use ‘mapTypeId’

• Use one of the following

– ROADMAP

– SATELLITE

– HYBRID

– TERRAIN

28

Map Types

29

Map Type

• Can also modify map type dynamically

– Map.setMapTypeId( ) method

30

Create Map Object

• Map class references the map

• Defines a single instance of a map

• Embedded inside the <div> container

– map_canvas

• Also pass in options that were defined

– myOptions

31

Loading the Map

• Map is first created in an initialization function

• Use onLoad attribute of the <body> tag

• The initialization function contains code that creates the map

32

Map Creation Process

Reference the Google Maps API

Specify a container for the map

Write JavaScript initialize function to create Map

Call initialize function when page body has loaded

4 Steps

Map Creation Process – In Code

Exercise Setup Instructions

• Before beginning work on any exercises in this course please follow the exercise setup

instructions.

35

Exercise

• Creating a Simple Google Map

• Please complete Exercise: Google Maps Basics

36

Exercise

• Using Map Options to Alter the Map

• Please complete Exercise: Map Options

37

Creating Map Controls

38

Adding Controls to the Map• Many controls can be added to the map

39

The Default UI

• Can elect to simply use the default user interface

– Zoom Control

– Pan Control

– MapType Control

• Don’t have to do anything in your code

40

Adding Controls to the Map

• Add to Map options literal

• Each control takes a true/false value indicating whether it should be displayed

41

Configuring Controls

• Controls are configurable

• Configuration is through

– ZoomControlOptions, MapTypeControlOptions,

PanControlOptions, ScaleControlOptions, RotateControlOptions,

OverviewMapControlOptions

• Should also enable the control

– zoomControl: true

– mapTypeControl:true

42

Configuring Controls

• Code example

43

ZoomControlStyle.SMALL

ZoomControlStyle.LARGE

ZoomControlStyle.DEFAULT

MapTypeControlStyle.HORIZONTAL_BAR

MapTypeControlStyle.DROPDOWN_MENU

MapTypeControlStyle.DEFAULT

Control Positioning

• Controls can also be positioned

• No absolute positioning

– Google Maps intelligently lays out the controls

• Control options object has a ‘position’ property

– Example:

• MapTypeControlProperties.position

44

Control Positioning

45Image provided by Google

Map Zoom Controls

• Zooming accomplished primarily with map controls

– Large or small control

– Size set with ZoomControlOptions and ZoomControlStyle

46

Pan Control

• Most common way to pan is to simply drag the map

• Can also pan with the Pan control

• Displays by default on large maps (larger than 400x350px)

– Will not display on smaller maps or mobile devices

47

MapType Control

• Controls base map

• Can be

– ROADMAP

– SATELLITE

– TERRAIN

– HYBRID

• Can also set style

– DROPDOWN_MENU

– HORIZONTAL

48

Overview Map Control

• Collapsible overview map

• Disabled and collapsed by default

• OverviewMapControlOptions

– Specify open or closed state

49

Scale Bar Control

• Provides a scale bar for your map.

• ScaleControlOptions

– Sets the position and style of the scale bar

50

StreetView Control

• Displays a Pegman icon

– Can be dragged onto the map to enable street view

51

Exercise

• Working with Map Controls

• Please complete Exercise: Map Controls

52

Adding Overlays to the Map

53

Overview of Overlays

• Overlays are objects you add to the map

– Points, lines, polygons, info windows, KML files, custom map types

• Points are most common and represented as Markers

• Info Windows display content about a location

• Can create custom overlay map types

54

Adding Overlays

• All overlay objects have an Options object

– Used in the construction of the overlay

– Can designate the map where they will appear

– Can also use the ‘setMap()’ method to add an overlay

55

Removing Overlays

• Overlays are removed by passing a null to the ‘setMap()’ method

– Example:

marker.setMap(null);

– This removes an overlay from the map but doesn’t delete it.

• To delete you must also set the overlay to null

56

Markers

• Identify locations on the map

• Use standard icon by default

– Can set custom icon

• Use Marker class

– Need position and map to construct the marker

57

Markers Are Interactive

• Markers are designed to be ‘clicked’

• Clicks are an example of an ‘Event’

– Events covered in detail later

• Display information about that location in an Info Window

58

Simple Marker Icons

• Can define custom icons in place of the default

• Simple Icons

– Use an image file to display instead of the default

pushpin icon

– Use the ‘icon’ property of Marker Options object

59

Complex Icons

• Can create more complex icons

– Complex shapes with clickable regions

– Shadow images

– Stack order in relation to other overlays

• Use MarkerImage object

60

Exercise

• Adding Markers to the Map

• Please complete Exercise: Adding Markers to the Map

62

Marker Info Windows

• Contain attribute information about the Marker

• Stem points to a location

– Usually a Marker but doesn’t have to be

• InfoWindowOptions object used to define

characteristics of the window including content

– Properties

• content

• position

63

InfoWindow Class

• Must call ‘open()’ to display InfoWindow

– Pass in map and anchor for the window

• Anchor is often a marker

– Often opened as a result of a ‘click’ event on a marker

• Can also

– Get and set content

– Control z-index

– Get and set the position of the stem

64

InfoWindow Content

String of text

HTML

DOM element

65

Exercise

• Adding an InfoWindow to Markers

• Please complete Exercise: Adding an InfoWindow to a Marker

66

Polylines

• Google Maps can also display lines, known as polylines.

• Represented by the Polyline object

• Composed of two or more points joined together by

a vector line

67

Polyline Options

• Polyline constructor takes a PolylineOptions object

– Defines

• LatLng coordinates of the line

• Set styling

– color, opacity, weight

68

Polygons

• The GPolygon class can be used to create polygonal area

– Created from an array of points

– First and last coordinates the same

• Closes the polygon

• Has a stroke (outline) and fill (enclosed region)

– Define color, width and opacity of stroke

– Define color and opacity of fill

69

Circles

• Similar to a Polygon

• Defined by

– Center

• LatLng object

– Radius

• In meters

70

Rectangles

• Similar to a Polygon or Circle

• Defined by a LatLngBounds object

71

Ground Overlays

• Loads an image on top of Google

Maps

• Image formats

– JPG/PNG/GIF

• Must specify

– URL to image

– LatLngBounds to represent extent

of image

72

Ground Overlays

73

Exercise

• Adding Ground Overlay Images

• Please complete Exercise: Adding Ground Overlay Images

74

Map Layers

75

Overview of Layers

• Additional layers can be added to the map

– KML Layers

– GeoRSS Layers

– FusionTables Layer

– Traffic Layer

– Bicycling Layer

76

KML Layers

• Google Earth format KML files can

be displayed in Google Maps

• Example in Google Maps

(here is the file in Google Earth)

– Use KmlLayer object

• Constructor takes a URL to a

publicly accessible KML file

• Converts KML objects rendered

as Google Maps objects

– All rendered as a single

object on the map

77

KML Layer Options

• KmlLayerOptions

– map

• The map where the KML layer should be displayed

– preserveViewport

• Map should be adjusted to the extent of the KML layer contents

– suppressInfoWindows

• Indicates if clickable features should trigger the display of InfoWindow objects

78

KML Layer Example

79

Accessing KML Features

• Individual features not accessed directly from KmlLayer object

• Rendered to “look like” Maps API overlays

• Clicking an overlay displays and InfoWindow

– Contains <title> and <description> information

– Also triggers KmlMouseEvent

• Passes information

– position

– pixelOffset

– featureData (JSON structure of KmlFeatureData

80

Exercise

• Loading KML Files in Google Maps

• Please complete Exercise: Loading KML Data into Google Maps

81

GeoRSS Layers

• GeoRSS layers handled just like KML layer

– Uses KmlLayer object

82

Fusion Table Layers

• Can render Fusion Tables as a FusionTablesLayerhttp://code.google.com/apis/fusiontables/

– Experimental at this time

• What is a Fusion Table?

– Database table containing data about a particular feature

– Location data

• FusionTablesLayer

– Interface to public Fusion Tables

– Automatic rendering of location data

– Clickable overlays

83

Fusion Tables

84

Fusion Tables Setup

• Fusion Tables provide built in geographic data support

• Must meet the following criteria

– Table must be shared as Public

– Must have a column or pair of columns containing location information

• Latitude, Longitude

• KML geometric data (<Point>, <LineString>, <Polygon>

• Location can be an address

– Must explicitly geocode addresses with Fusion Tables

» File Geocode

85

Fusion Tables ID

• Each Fusion Table has a unique ID

– File About in Fusion Table

interface

• Need this ID when creating a

FusionTablesLayer in Google Maps

86

FusionTablesLayer

• Use FusionTablesLayer constructor with the unique ID to create a layer

87

Fusion Table Queries

• Restrain result set for your map with a query

• Use the ‘query’ parameter

– Standard SQL query

• SELECT <locationColumn> from <fusionTable> WHERE <constraint>

• SELECT address FROM 173112 WHERE state = ‘California’

88

Fusion Table Heatmaps

• Fusion Tables provides rudimentary heat map

capabilities

• Uses color palette

– Red – green gradient

– Red = dense, green = sparse

• Use ‘heatmap’ parameter

89

Exercise

• Adding a Fusion Table to Google Maps

• Please complete Exercise: Adding a Fusion Table to Google Maps

90

Traffic Layer

• Real time traffic information

– Snapshot based on the current request

• Does not cover all areas

http://gmaps-

samples.googlecode.com/svn/trunk/mapcoverage_filtered.html

• TrafficLayer object

91

Bicycling Layer

• BicyclingLayer renders

– Bike paths

– Suggested bike routes

– Other overlays specific to bicycling usage

• Emphasizes streets friendly to bike routes

92

Module 3: Google Maps Events

E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com

Module Outline

• What are Events?

94

What are Events?

95

What are Events?

• Events are actions that take place within an application

– Map clicks, mouse drags (panning), keyboard actions, component modification

(resizing), network traffic (sending, receiving data), and others

– MVC state changes

• Event.addListener() used to connect an event with a handler

• Event handlers respond to the events

– JavaScript function executes

96

•Mouse click

•Keyboard interaction

Event Occurs

Connects an event to a

handlerListener

Runs in response to the event

Handler

Event Handling

97

• Mouse click

• Keyboard interaction

Event Occurs

Connects an event to a

handlerListener

Runs in response to the event

Handler

Handler

Connects Event to Handler

Should I Handle All Events?

• Not necessary to write code for all events

– Only those necessary for your application

– What happens when an event occurs for which you haven’t written a handler?

• Nothing. Event is ignored in your application

98

Event Types

• 2 types of events

1. User Interface (UI) Events

• User generated events such as map clicks, drags etc

• Map, Marker, Polygon, GroundOverlay, others

• Often pass an event to the handler

2. MVC Events

• System or application generated

• Reflect changes in Maps API objects

• Do not pass an event to the handler

99

UI Events

• Map and Marker have many different types of events

• Marker

– ‘click’, ‘dblclick’, ‘mouseup’, ‘mousedown’, ‘mouseover’, ‘mouseout’, many

others

• Map

– “click’, ‘dblclick’, ‘mouseup’, ‘mousemove’, ‘mouseover’, many others

• Many other objects have UI events

100

MVC State Changes

• MVC objects usually contain state

• When object property changes, the API fires an event that the property has

changed

• Don’t pass arguments

• Example

– Map.center_changed

• Map object keeps track of the center point of the map

• When this changes the center_changed event is fired

101

Registering an Event

• Use Event.addListener()

102

Event Arguments

• UI Events often pass an ‘event’ argument to the listening function

– Does not apply to MVC state changes

• This ‘event’ argument can be accessed by the listener

• Example:

– Map.click event passes a MouseEvent containing the latLng property where the

map was clicked

103

Removing Event Listeners

• If you no longer need a listener it is best to remove it

event.removeListener(listener);

104

Exercise

• Working with Events

• Navigate to your c:\GeoSpatialTraining\GoogleMapsAPIv3\Exercises directory

– Open “Exercise_Responding_To_Events.pdf

105

Module 4: Geocoding Service

E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com

Module Outline

• What is Geocoding?

• The Geocoding Process

• Creating Bias in Geocoding Results

• Reverse Geocoding

What is Geocoding?

108

What is Geocoding?

• Plotting points of interest on a map is perhaps the most commonly used function in Google Maps.

• To plot these points you must have latitude, longitude coordinates.

• Address coordinates are generated through a process known as geocoding.

• Geocoding is a process that interpolates the geographic location (latitude, longitude) of an address.

109

What is Geocoding?

• After an address has been geocoded

(assigned a latitude, longitude

coordinate) it can be plotted as a

map overlay in Google Maps.

• Typically, these are represented by

some sort of marker icon.

Geocoding Accuracy Levels

Rooftop

Street Segment

Geometric Center

Approximate

High PrecisionFallback

111

Low Precision

Rooftop Geocoding

• Also called “point-level” geocoding

• Most accurate determination

• More accurate for long street segments, cul-de-sacs, or irregularly spaced addresses

• Assigns a geographic coordinate to the actual rooftop of an address

112

Street Segment Geocoding

• Assigns latitude/longitude coordinates based on know geocodes at the intersection of the block or street segment containing an address

• Uses a process of interpolation

– Example: If a block runs from 100-200 Main Street, then 150 Main Street would be approximately halfway between 100 and 200 Main Street

• Most commonly used method at this time

• More accurate in urban areas

– Rural areas are less complete

113

Main St.

100 200150

Longitude: -96.3462, Latitude: 20.4521

The Geocoding Process

114

Geocoding Process

GeocoderRequest Geocoder GeocoderResults

115

Geocoding Process

Geocoder

Address

Callback

FunctionLatLng

1600 Amphitheatre Pkwy, Mountain View, CA

GeocodeRequest

• Object literal

• Only required parameter is

– Addresss OR LatLng

• An address indicates a regular geocoding operatation

• A LatLng indicates a reverse geocode

117

GeocodeRequest Geocoder GeocoderResults

Geocoder

• Sends a geocode request to the Google servers

• One method

– Geocoder.geocode()

118

GeocoderRequest Geocoder GeocoderResults

GeocoderResults

• Geocoding service returns

– Results

• Object literal

• May contain more than

one result

– Status code

119

GeocoderRequest Geocoder GeocoderResults

Deciphering the GeocoderResults Object

120

GeocoderResults

[GeocoderAddressComponent] GeocoderGeometry

GeocoderLocationType

GeocoderAddressComponent

• Each GeocoderAddressComponent object stored in

an array

– short_name

• Short abbreviated text of the address

– long_name

• Full text of the address

– types

• Array of strings denoting the type of address

121

GeocoderAddressComponent: Address Types

• The types[] array indicates the address type

– May have multiple types

• Example: street_address, political, and locality

• Some examples include:

– street_address, route, intersection, political, locality, neighborhood

• Get the full list of address typeshttp://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingAddressTypes

122

GeocoderGeometry

• Contains information about the geometry

of the geocoded address

– location

• LatLng

– location_type

• GeocoderLocationType

– viewport

• LatLngBounds

– bounds

• LatLngBounds

123

GeocoderLocationType

GeocoderResults

GeocoderGeometry

GeocoderLocationType

124

• APPROXIMATE

• GEOMETRIC_CENTER

• RANGE_INTERPOLATED

• ROOFTOP

Status Codes

• Status code also returned to callback function

– GeocoderStatus object

• Can be one of the following:

– GeocoderStatus.OK

– GeocoderStatus.ZERO_RESULTS

– GeocoderStatus.OVER_QUERY_LIMIT

– GeocoderStatus.REQUEST_DENIED

– GeocoderStatus.INVALID_REQUEST

125

Exercise

• Geocoding Addresses

• Please complete Exercise: Geocoding Addresses

126

Creating Bias in Geocoding Results

127

Creating a Viewport Bias

• Instruct geocoding service to prefer results within a geographic extent

– Use ‘bounds’ parameter in GeocodeRequest object

• Geographic bounding box

• LatLngBounds

128

Creating a Region Code Bias

• Can instruct geocoding service to bias results toward

a geographic region

• Parameter takes a region codehttp://www.iana.org/assignments/language-subtag-registry

129

Reverse Geocoding

130

Reverse Geocoding

• Takes a geographic location (LatLng) and returns the nearest address

• Pass LatLng object into Geocoder.geocode

131

Reverse Geocoding Results

• Reverse geocoder often returns more than one result

– Complete address, City- State-Country, City-Zip-Country, City-Country, Country

• Results contained within an array

– Ordered from best to worst

– results[0].formatted_address: “1202-1210 Sand Wedge, San Antonio, TX 78258, USA",

results[1].formatted_address: “San Antonio, TX, USA",

results[2].formatted_address: “San Antonio 78258, USA",

results[3].formatted_address: “San Antonio, USA",

results[4].formatted_address: “Texas, USA",

results[5].formatted_address: "United States"

132

Exercise

• Reverse Geocoding

• Please complete Exercise: Reverse Geocoding

133

Module 5: Google Maps Elevation Service

E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com

Introduction to the Elevation Service

• Provides elevation data for locations

on the Earth’s surface

• Also provides sampled elevation data

along paths

• ElevationService object

135

Elevation Service Process

LocationElevationRequestor

PathElevationRequest

ElevationService ElevationResult

136

Elevation Requests

• Can be:

– LocationElevationRequest

• Takes an array of discrete LatLng objects

– PathElevationRequest

• Takes an array of LatLng objects that define the path

• Also accepts a value that indicates the number of samples to take along the path

• Request object passed into the ElevationService object

137

ElevationService

• Elevation requests are submitted through the ElevationService object

• 2 methods

– getElevationAlongPath( )

– getElevationForLocations( )

• Both accept their associated Request object along with a callback function

138

ElevationResult

• Results of an elevation service request are contained in an ElevationResult

object

– Single request can produce multiple ElevationResult objects

• Properties

– elevation

• Elevation, in meters, above sea level, for the location

– location

• LatLng of the elevation result

139

ElevationStatus

• Contains the status of the request

• Constants

– INVALID_REQUEST

– OK

– OVER_QUERY_LIMIT

– REQUEST_DENIED

– UNKNOWN_ERROR

140

Code Example

141

Exercise

• Elevation Service

• Please complete Exercise: Using the Elevation Service

142