advanced google maps api programming (v3)s3.amazonaws.com/virtualgisclassroom/advanced google maps...
TRANSCRIPT
Advanced Google Maps API Programming (v3)
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Module Outline
• Module 1: The Google Maps Utility Library
• Module 2: Custom Tile Overlays
• Module 3: Geometry Library
• Module 4: Directions Service
• Module 5: StreetView Service
• Module 6: Development for Mobile Devices
2
Module 1: The Google Maps Utility Library
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Introduction to the Utility Library
• Open source JavaScript library
• Contains utilities not part of the core Google Maps API
• Marker Manager
• MarkerClusterer
• MarkerWithLabel
• StyledMarker
• InfoBox
• Google Earth
• Others (Full List here)http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries
4
Referencing a Class from Utility Library
• You must provide a specific reference to the class you want to use
http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js
5
The Marker Manager
• Used to efficiently display hundreds of markers on the map
• Also used to reduce visual clutter at certain map scales
– Specify the zoom scale at which markers will appear
• MarkerManager class in markermanager.js library
6
How the Marker Manager Works
• MarkerManager places all markers onto a grid that covers the map
• When user moves the display (zooming or panning)
– MarkerManager computes grid cells that have entered or left the display
– Shows or hides all the markers in those cells
• May have 1,000’s of markers in your application
– As long as only 100-200 are visible at any one time performance is good
7
Creating the Marker Manager
• How to access
<script src=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js></script>
• MarkerManager class
– Create a new instance of MarkerManager
• Simple
• With MarkerManagerOptions
8
MarkerManagerOptions
• Used for fine grained control of MarkerManager
• Available settings
– maxZoom
• Max zoom level monitored by the marker manager
• Used to control clutter
– borderPadding
• Specifies extra padding, in pixels, monitored by the manager outside the current viewport
• Used to display markers just beyond the current viewport
• Improves small distance panning
– trackMarkers
• Specifies whether movement of movements of markers should be tracked
• Used when your markers change position
• By default set to ‘false’
• Object literal; no constructor
9
Adding Markers to MarkerManager
• The addMarker() method is used to add a single marker to MarkerManager
• The addMarkers() method is used to add a collection of markers contained within an
array
– More efficient
– Markers appear collectively when MarkerManager.refresh() is called
10
Removing Markers
• To remove markers from MarkerManager
– removeMarker(marker)
• Removes a specific marker
– clearMarkers()
• Removes all markers
11
Controlling MarkerManager Visibiliy
• To hide the MarkerManager
– MarkerManager.hide();
• To show the MarkerManager (visible by default)
– MarkerManager.show();
• Toggling visibility
– MarkerManager.toggle();
• Checking for visibility
– MarkerManager.visible(); //return true or false
– MarkerManager.isHidden(); //returns true if hidden
12
Exercise Setup Instructions
• Before beginning work on any exercises in this course please follow the exercise setup
instructions found near the top of the course.
13
Exercise
• In this exercise you will learn how to use the MarkerManager utility class to add a large
number of points to the Google Maps display.
• Please complete – Exercise: Using the MarkerManager Utility Class to Load Many
Markers
14
MarkerClusterer• Common Problem
– You need to add thousands of markers to your Google Maps application
– Application performance suffers; map looks cluttered
– MarkerManager is one solution
• Handles performance but not clutter
• MarkerClusterer is the solution
– Collects neighboring markers into different clusters
– Displays the number of markers in each cluster with a label
15
More on MarkerClusterer
• Groups markers into clusters according to distance from a cluster center
• Marker is added to map
– Clusterer finds a position in all clusters and if it fails to find one, creates a new cluster
• When map viewport changes, MarkerClusterer destroyed clusters and regroups into
new clusters
16
Creating MarkerClusterer: The Simple Method
• Several methods to create MarkerClusterer
– Simple method
• Pass an instance of Map to MarkerClusterer constructor
• Pass in array of Markers
• View example (provided by Google)http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/examples/simple_example.html
Creating a MarkerClusterer with MarkerClustererOptions
• Can also use MarkerClustererOptions
• Common options
– Grid size
– Max zoom
– Styles
• Pass array of Markers into constructor
18
MarkerClusterer Class
• Number of methods provided
– addMarkers(markers: Array of Gmarker)
• Adds an array of markers to the display
– clearMarkers()
• Removes all markers from the display
– getTotalClusters()
• Returns total number of clusters
– removeMarker(marker:GMarker)
– resetViewport()
• Used to regroup markers into new clusters
• Perhaps done after removing some markers
19
MarkerClustererOptions
• Provides optional arguments to MarkerClusterer
– gridSize
• Grid size of a cluster
• In pixels (default is 60)
• Algorithm runs faster if value is larger
– maxZoom
• The max zoom level monitored by a marker cluster.
– Default is maximum zoom level
– When maxZoom is reached or exceeded all markers will be shown without cluster.
– styles
• MarkerStyleOptions
– Image height and width
– Text Color
– URL to image
20
Exercise
• In this exercise you will learn how to use the MarkerClusterer class.
• Please complete – Exercise: Using MarkerClusterer
21
MarkerWithLabel
• Associates a label with a Marker
• Otherwise it’s just like a Marker object
• Can use CSS to style the text
22
StyledMarker
• Extension of basic Marker class
– Use StyleIcon to change display aspects of Marker
– Can change
• Color
• Shape
• Text
23
InfoBox
• Similar to an InfoWindow
– Supports advanced styling
• Use InfoBoxOptions to define options
http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/docs/reference.html#InfoBoxOptions
• Content can be plain text or DOM node
• View code examples
http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/docs/examples.html
24
GoogleEarth
• GoogleEarth object used to render
GE in Google Maps application
• Also supports
– Marker
– InfoWindow
– Polyline
– Polygon
– Rectangle
– Circle
– GroundOverlay
– KmlLayer
25
Module 2: Custom Tile Overlays
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Google Maps Tiling
• Google Maps are produced in advance and served as image tiles
– Multiple tiles per view
– 256 x 256
– Tiles are stitched together on the client to form one large image
• Tiles fetched according to zoom value + coordinate system
• Great performance, consistent appearance, graphical quality
• Big effort to pre-generate tiles at all levels
X,Y Coordinate
System
Zoom Value
Tiles to Fetch
What are Custom Tile Overlays?
• Custom data that overlays existing Google Maps
• Snapshot of your data at a particular time
• Data is cut into a pyramid of tiles that correspond to each zoom level
Why Custom Tile Overlays?
• Used to overlay custom data on Google Maps
• Why not just add custom data as markers, polylines, polygons?
– Performance better with custom tile overlays
• Downside?
– Can’t obtain information about the custom data
• Can’t click a marker to see InfoWindow
OverlayView Class
• Used to create your own custom overlays
• OverlayView is a base class
– Must implement several methods
• Process
1. Set custom object’s prototype to new instance of OverlayView (Subclassing an Overlay)
2. Create constructor for custom overlay; set initialization parameters
3. Implement onAdd() method on prototype
4. Implement draw() method on prototype
5. Implement onRemove() to clean up
30
Creating a Custom Overlay - Example
• USGS Overlay Examplehttp://code.google.com/apis/maps/documentation/javascript/examples/overlay-hideshow.html
31
The Initialize() Function
32
SubClassing OverlayView
33
Initializing the Overlay
• Overlay needs to be attached to the map
• Added to a Map Pane
– Many panes
– Like ‘layers’
• Stacking order
• Done in .onAdd() method
34
Initializing the Overlay
35
Drawing the Overlay
• Draw() method used to actually draw the image on the map
36
Removing an Overlay
• The ‘onRemove()’ method removes an overlay from the map
• Invocked when overlay’s map property set to null
37
Exercise
• In this exercise you will learn how to create a custom overlay
• Please complete – Exercise: Creating a Custom Overlay
38
Module 3: The Geometry Library
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Introduction to the Geometry Library
• Utility functions for computation of geometric data
• Two namespaces
1. Spherical
• Computes angles, distances, and areas from latitudes and longitudes
2. Encoding
• Used for encoding and decoding polyline paths
• No classes, just static methods
• How to reference geometry library?
– Attach &libraries=geometry to reference for the Maps API
40
Spherical Geometry
• Google Maps application is 2-D or “flat”
– Earth is 3-D or spherical
• Maps API uses a sphere to represent Earth on 2D surface (uses a projection)
– Projection creates distortion
• Euclidean geometry not applicable
• Geometric function on a sphere need Spherical Geometry to calculate distance and area
41
Distance and Area Functions
• Distance between two points
– Use computeDistanceBetween() method
• Calculate length of a path (multiple points)
– Use computeLength() method
• Compute area of a polygon
– Use computeArea()
• Uses array of LatLng objects defining a closed loop
42
Exercise
• Calculating the length of a path
43
Navigation Functions
• Heading is the angle of a direction from a fixed reference point (usually true north)
– Measured clockwise with 0 degrees being true north
– Used in navigation
– Use computeHeading() method
• Pass in two LatLng objects
44
Navigation Functions
• Other methods
– computeOffset()
• Calculate destination coordinates given:
– Particular heading, origin location, distance to travel
– interpolate()
• Calculates a destination between two LatLng objects given:
– Two LatLng objects and value between 0 and 1
45
Encoding Methods
• Paths (polylines) in Maps API created with an array of LatLng objects
– Array can get large and affect performance
• Can use Google’s polyline encoding algorithm to compress a path
– Called encoding
– Deocoding decompresses the path
46
Module 4: The Directions Service
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Directions Service Overview
• Used to calculated directions
– Can use variety of transportation methods
• Car
• Public Transportation
• Walking
• Cycling
• Uses a DirectionsService object
• Results returned as DirectionsRenderer object
– Contains a polyline of the route
– Also a textual description
48
v
Directions Process
49
DirectionsService
route(directionsRequest)
Directions Service
DirectionsRequest
callback(results)
DirectionsResult
DirectionsService Object
• Facilitates the request and response processing of a directions request
• The ‘route()’ method sends the request
50
DirectionsRequest Object – Required Fields
51
• Contains following fields:
– origin
– destination
– travelMode
– unitSystem
– waypoints[]
– optimizeWaypoints
– provideRouteAlternatives
– avoidHighways
– avoidTools
– region
DirectionsRequest Optional Fields: unitSystem
• unitSystem
– Units of measure to display with results.
– By default uses origin’s country or region.
– Can be Metric or Imperial
• Metric is meters
• Imperial is English or miles
52
DirectionsRequest Optional Fields: Waypoints
• 2 waypoint fields
• Waypoints[]
– An array of DirectionsWaypoints
– Alter a route by routing through specified waypoints
• optimizeWaypoints
– True/false value
– If waypoints being used is used to specify the shortest possible route
53
DirectionsRequest Optional Fields: Alternative Routes
• Need a choice of routes?
• provideRouteAlternatives
– True/false value
• Directions service may provide more than one possible route to the destination
54
DirectionsRequest Optional Fields: Avoid Highways and Tolls
• Want the route to avoid highways and/or tolls
• avoidHighways
– Set to true to avoid
• avoidTolls
– Set to true to avoid
55
DirectionsResult
• Response from Directions Service is a DirectionsResult object
– DirectionsStatus code also returned
• Need to inspect DirectionsStatus before attempting to process DirectionsResult
– OK
– NOT_FOUND
– ZERO_RESULTS
– MAX_WAYPOINTS_EXCEEDED
– INVALID_REQUEST
– OVER_QUERY_LIMIT
– REQUEST_DENIED
– UNKNOWN_ERROR
56
Processing DirectionsResult
• DirectionsResult contains results of directions query
– Can handle results in your code or pass to DirectionsRenderer object
• DirectionsRenderer automatically displays the result
– How to display results using DirectionsRenderer?
1. Create DirectionsRenderer object
2. Call setMap() on the renderer to bind to Map
3. Call setDirections() on renderer passing in DirectionsResult
– Code example on next slide
57
Processing DirectionsResult with DirectionsRenderer
58
http://code.google.com/apis/maps/documentation/javascript
/examples/directions-simple.html
More on the DirectionsResult Object
• May need to inspect the contents of a DirectionsResult
• DirectionsResult contains a single field within an object literal
– routes[ ]
• An array of DirectionsRoute objects
• Each DirectionsRoute object is a way to get from the origin to the destination
• Only one route unless ‘provideRouteAlternatives’ is set to true on the DirectionsRequest
59
DirectionsRoute
60
DirectionsRequest DirectionsRoute DirectionsLeg
DirectionsStep
View an example
http://code.google.com/apis/maps/documentation/javascript/examples/directions-complex.html
Module 5: The StreetView Service
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Street View
• Street View functionality allows developers to include street
visualizations natively in browser
• Available in most of the United States
– Street View button
• Street View capability indicated by blue outline
• See a demonstration
StreetView Panoramas
• StreetViewPanorama object is interface to Street View “viewer”
• Map contains default panorama
– Map.getStreetView()
– Can also create your own StreetViewPanorama
• Add Street View control through options
– Adds the pegman
63
StreetViewPanorama
64
Code Example
65
StreetViewOptions
• PanoramaOptions define options for the Panorama
– Position property
• Controls placement of the camera (LatLng object)
– StreetViewPov object
• Heading
– Rotation angle of the camera in degrees (0-360) 0 is true north
• Pitch
– Angle of the camera; -90 is straight up and +90 is straight down, 0 is horizontal
• Zoom
– Zoom level of the view; 0 is fully zoomed out
66
StreetView Overlays
• Markers, InfoWindows and custom OverlayViews can overlay Street View
• Appear at street level
– Anchored by LatLng points
67
Street View Events
• pano_changed
• position_changed
• pov_changed
• links_changed
• visible_changed
68
Street View Controls
• Several controls added to StreetViewPanorama
• Can be enabled or disabled with
StreetViewPanoramaOptions
– panControl
– zoomControl
– addressControl
– linksControl
69
zoomControl
panControl
linksControl
addressControl
Street View Service Requests
• 2 types of service requests to StreetViewService
– getPanoramaById()
• Returns panorama data corresponding to unique ID of the panorama
– getPanoramaByLocation()
• Searches for panorama data around a point (LatLng) and a radius (meters)
• Asynchronous requests
– Must provide callback function
70
Street View Service Responses
• StreetViewPanoramaData object returned to the callback function
– Contains metadata about Street View panorama
– Also returns StreetViewStatus
• StreetViewStatus
– OK
– ZERO_RESULTS
– UNKNOWN_ERROR
• StreetViewPanoramaData is only metadata
– Must use location.pano with StreetViewPanorama.setPano() to actually create a new
panorama
71
Exercise
• Please complete the exercise: Displaying Street View in Google Maps
72
Module 6: Development for Mobile Devices
E-Learning for the GIS Professional – Any Time, Any Place!geospatialtraining.com
Overview of Google Maps for Mobile
• Version 3 designed specially designed to be faster on mobile devices
• Loads fast
• Focused on iPhone and Android devices
74
General Recommendations
• Set the <div> container for your map with height and width attributes of 100%
• Detect iPhone and Android devices with navigator.userAgent
75
General Recommendations
• iPhones also support the following <meta> tag
• Setting specifies map should be displayed full-screen and not resizable by user
76