Google Maps

advertisement
Introducing Google Maps South Africa
Jarda Bengl Business Product Manager
Russell Middleton Customer Solutions Engineer
Google Confidential and Proprietary
1
Agenda
1. Maps API 101
2. Sharing Geo data between applications (using KML)
3. Cool features
 Local Search
 Static Maps
 Location Detection
 Custom Tile Layers
 Flash API
 Reverse Geocoding
 Wikipedia and Panoramio Layers
 Street View
 Earth API
Google Confidential and Proprietary
2
Maps API 101
The crash course
Google Confidential and Proprietary
3
Google Maps 101: Adding a map to your page
1. CSS / HTML: Define a map container
#map { height:400px; width:400px; border:1px solid grey; }
<div id='map'></div>
2. Use the Google AJAX API Loader
<script type='text/javascript'
src='http://www.google.com/jsapi?key=ABCDEFG'>
<script>google.load('maps', '2.x');</script>
3. Create the map
var map = new GMap2(document.getElementById('map'));
4. Add controls
map.addControl(new GLargeMapControl());
map.addControl(new GHierarchicalMapTypeControl());
5. Initialise the map
var lat = 51.49494; var lng = -0.14657; var initialzoom = 17;
map.setCenter(new GLatLng(lat, lng),initialzoom);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
4
Google Maps 101: A note on the AJAX loader
Loading the Maps API is a two step process:
1. Loading the AJAX loader library
<script type='text/javascript' src='http://www.google.com/jsapi?key=ABCDEFG'>
2. Loading the Maps API
<script>google.load('maps', '2.x');</script>
 Using the loader makes it easier to load in our other Google AJAX APIs, like
the Local Search API or the Earth API
 You can also opt to load the Maps API asynchronously after the body load, by
specifying a callback function in the options to the loader. This is useful for
loading the Maps API after the user has initiated some action:
<script>google.load('maps', '2.x', {callback:loadMaps});</script>
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
5
Google Maps 101: Adding a marker
1. Initialise the marker
var marker = new GMarker(new GLatLng(lat, lon));
2. Make a bubble pop up when clicked
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml('<h1>London
Googleplex</h1><p>Welcome!</p>');
});
3. Display the marker
map.addOverlay(marker);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
6
Google Maps 101: Adding a line
1. Initialise lat/lon offset from our marker (optional)
var latOffset = 0.001;
var lngOffset = 0.001;
2. Create the line
var line = new GPolyline([new GLatLng(lat, lng-lngOffset),
new GLatLng(lat, lng+lngOffset)]);
3. Display the line
map.addOverlay(line);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
7
Google Maps 101: Adding a polygon
1. Create the polygon and set line / fill properties
var polygon = new GPolygon([
new GLatLng(lat, lng - lngOffset),
new GLatLng(lat + latOffset, lng),
new GLatLng(lat, lng + lngOffset),
new GLatLng(lat - latOffset, lng),
new GLatLng(lat, lng - lngOffset)],
'#f33f00', 5, 1, '#ff0000', 0.2);
2. Display the polygon
map.addOverlay(polygon);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
8
Google Maps 101: Geocoding an address
1. Define the address to be geocoded
var address1 = '1 Strand, London';
2. Create the GClientGeocoder object
var geocoder = new GClientGeocoder();
3. Geocode the address and place a marker
geocoder.getLatLng(address1, function(point) {
map.setCenter(point,initialzoom);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml('<h1>1 Strand</h1>
<p>London</p>');
});
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
9
Google Maps 101: Directions
1. CSS / HTML: Define a text directions container
#directions { width:400px;}
<div id = 'directions'></div>
2. Define the address(es) to be geocoded
address2 = '76 Buckingham Palace Road, London'
3. Create the GDirections object
gdir = new GDirections(map,directions);
4. Compute and display the directions
gdir.load('from: ' + address1 + ' to: ' + address2);
Note: to show walking directions, use
gdir.load('from: ' + address1 + ' to: ' + address2,
{travelMode:G_TRAVEL_MODE_WALKING});
Live Demo
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
10
Sharing Geo data between applications
Using KML
Google Confidential and Proprietary
11
KML: Introduction
Keyhole Markup Language (KML) is an XML-based language for
expressing geographic annotation and visualization
Developed for use with Google Earth (originally named ‘Keyhole Earth Viewer’)
Became an official standard for geobrowsers in April 2008
KML files specify a set of ‘place’ features (placemarks, images, polygons,
3D models, textual descriptions, etc.) and views
Each place has a longitude and a latitude
Views can be defined in terms of tilt, heading and altitude
KML files are very often distributed as KMZ files, which are zipped KML
files with additional images and assets
Google Confidential and Proprietary
12
KML: Placemarks
In this example, we create a placemark with a name, description and altitude
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2'>
<Placemark>
Headers
Placemark definition
<name>Simple placemark</name>
Placemark name
<description> <![CDATA[
<h1>CDATA Tags are useful!</h1>
<p><font color='red'>Text is <i>more readable</i> and
<b>easier to write</b> when you can avoid using entity
references.</font></p>
]]>
</description>
Placemark HTML
description
<Point>
<coordinates>-122.0.4,0</coordinates>
Placemark lat/long/altitude
</Point>
</Placemark>
</kml>
Google Confidential and Proprietary
13
KML: Paths
Now we create a path at altitude, extended down to the ground
<Placemark>
Placemark definition
<name>Extruded path</name>
Placemark name
<description>Path extended to the ground</description>
Placemark name
<LineString>
Line definition
<extrude>1</extrude>
Extend down to the ground
<tesselate>1</tesselate>
Break into smaller chunks
<coordinates>
-112.2550785337791,36.07954952145647,2357
-112.2549277039738,36.08117083492122,2357
-112.2552505069063,36.08260761307279,2357
-112.2564540158376,36.08395660588506,2357
</coordinates>
Coordinate lat/long
</LineString>
</Placemark>
Google Confidential and Proprietary
14
KML: Styles
Finally, we define a style and attach it to a placemark
<Style id='yellowLineGreenPoly'>
Style definition
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
Line style definition
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
Polygon style definition
</PolyStyle>
</Style>
<Placemark>
Placemark definition
<styleUrl>#yellowLineGreenPoly</styleUrl>
Link to style
…
Placemark details
<Placemark>
Google Confidential and Proprietary
15
KML: Network links
Network links allow content to be updated, based on data/algorithms hosted elsewhere
<Folder>
Folder definition
<name>Network Links</name>
Folder name
<description>Network Links Example</description>
Folder description
<NetworkLink>
Network Link definition
<name>Random Placemark</name>
Network Link name
<description>A simple server-side script that generates a new
random placemark on each call</description>
Network Link description
<Link>
Link definition
<href>http://api.flickr.com/services/feeds/geo/?id=5870527
8@N00&lang=en-us&format=kml_nl</href>
Link URL (generates KML)
</Link>
</NetworkLink>
</Folder>
Example: http://www.flickr.com/photos/medabeda/
Google Confidential and Proprietary
16
KML: What to do with it
KML can be displayed in Google Maps, Earth and Static Maps
and other compatible geo applications
1. Display it in Google Maps
var kml = new GGeoXml('http://mydomain.com/myfile.kml');
map.addOverlay(kml)
 Can also view by pasting the URL into the Maps Search box
2. Display it in Google Maps for Mobile
 Clicking a link to a KML document should open Google Maps for
Mobile (if installed)
3. Display it in Google Earth
 Google Earth identifies itself with KML file types
 Contents can be saved in the ‘Places’ menu
 KML can be added as an overlay in the Google Earth browser API
The KML Generator is a great way to learn
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
17
KML: Submit it to Google!
KML can be submitted to the Google index, making it discoverable from
google.com and maps.google.com
1. Create the KML content and include attribution tags
<atom:author>
<atom:name>J. K. Rowling</atom:name>
</atom:author>
<atom:link href='http://www.harrypotter.com' />
2. Add a reference to the KML to your Sitemap file
<url>
<loc>http://www.example.com/example1.kml</loc>
<geo:geo>
<geo:format>kml</geo:format>
</geo:geo>
</url>
3. Submit the Sitemap to Google
 Submit your Sitemap using Google Webmaster Tools
Google Confidential and Proprietary
18
Cool features
Local Search
Static Maps
Location Detection
Custom Tile Layers
Flash API
Reverse Geocoding
Wikipedia and Panoramio Layers
Street View
Earth API
Google Confidential and Proprietary
19
Local Search: Introduction
Many map developers want to let users easily search for businesses
The Local Search API lets you do this, but requires lots of implementation
google.load('search', '1');
function OnLoad() {
var searchControl = new google.search.SearchControl();
Initialize AJAX Search
var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(localSearch);
Initialize
localSearch.setCenterPoint("New York, NY");
Set center point
searchControl.draw(document.getElementById("searchcontrol"));
searchControl.execute(“Pizza Johannesburg");
}
google.setOnLoadCallback(OnLoad);
Display
Local Search API http://www.google.com/uds/samples/random/lead.html
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
20
Local Search: GoogleBar
The GoogleBar simplifies matters
Just one line of code to add:
GoogleBar Demo
map.enableGoogleBar();
 This turns the boring Google logo
into a shiny new search box, which
uses the Local Search API to return
results
 Using GGoogleBarOptions, you can
tweak the placement and type of
results offered
Key:
Javascript
CSS
HTML
Example implementation
Google Confidential and Proprietary
21
Static Maps API: Introduction
The full Javascript Maps interface takes time to load

Scripts to process

Large images to download
Solution: The Static Maps API reduces load time by displaying a static image,
rather than the full Javascript Maps interface
When to use?

When the map isn’t the main focus of a page, and many users will not
interact with it

If you cannot be sure the user has a Javascript-enabled browser

On mobile sites, where many users will not have a Javascript-enabled
browser, and connections are slow
The Static Maps API can be combined with the Javascript API
for a better user experience
Google Confidential and Proprietary
22
Static Maps API: Examples
1) Lonely Planet Mobile (http://m.lonelyplanet.com/)
Displays static map of current user location
Plots nearby places to ‘sleep’, ‘play’, ‘eat’, ‘shop’ and ‘see’
Links to Lonely Planet review on each date
2) Orbitz Mobile Update
(http://updates.orbitz.com/mobile/)
Generates static map of traffic incidents
Collects input from mobile users
Google Confidential and Proprietary
23
Static Maps API: Implementation
Good news! Just add an <img> tag pointing
to a well-crafted URL
e.g. <img src=
'http://maps.google.com/staticmap?center=23.5,46.6&zoom=10&size=300x200&markers=23.6,-46.6&key=ABCDEFG'>
You can specify a number of map arguments in the URL

Required: Center, Zoom, Size, Key

Optional: Format, Maptype, Markers, Path, Frame
Even better news! URLs can be generated in the Google Static Map Wizard
Google Confidential and Proprietary
24
Static Maps API: Tips and tricks
The Static Maps API can be combined with the Javascript API
for a better user experience
1. Start with a static map, loading JS API only if user interacts with it

e.g. Gumtree Property Listings
(http://www.gumtree.com/london/98/28643598.html)
2. Load the full page, then append the Maps code (so map only loaded
after rest of page)

e.g. nearby.org.uk (http://www.nearby.org.uk/google/static4.php)
Google Confidential and Proprietary
25
Location Detection: Introduction
Until recently, the user had to centre/zoom on their location themselves

This was time-consuming and potentially repetitive for regular visitors
Solution: Automatic location detection in the AJAX API
Three alternatives

HTML5 includes location detection (works with Firefox 3.5 and Chrome)

Gears includes location detection through best available method
 IP address, WiFi signal strength, cell ID, GPS, etc

AJAX loader attempts to geolocate the user by IP address
 When an application uses the AJAX API loader, the loader attempts to
geo locate the client based on it's IP address
 If this process succeeds, the client's location is made available in the
google.loader.ClientLocation property
 If the process fails to find a match, this property is set to null
Google Confidential and Proprietary
26
Location Detection: Implementation
1. Check if ClientLocation object is defined
if (google.loader.ClientLocation) {
var lat = google.loader.ClientLocation.latitude;
var lng = google.loader.ClientLocation.longitude;
}
2. If not, set lat/long manually
else {
var lat = 51.0;
var lng = 0.0;
}
3. Centre the map
map.setCenter(lat,lng);
You can also access:
ClientLocation.address.city
ClientLocation.address.country
ClientLocation.address.country_code
ClientLocation.address.region
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
27
Custom Tile Layers: Introduction
The Google Maps interface can be used to browse multi-resolution
images by defining a custom map type
All non-geocoding Maps functionality can be used with custom tile layers
Multiple rescaled images are required, corresponding to map zoom levels
 Each image must be divided into a grid of square tiles
One Prague Map charts house prices
Another charts beer prices
Google Confidential and Proprietary
28
Custom Tile Layers: Example
Kremer Collection Photography (www.thekremercollection.com)
Map navigator and
zoom level control
Orientation
navigator
Content copyright notice
Google Confidential and Proprietary
29
Custom Tile Layers: Implementation (1)
1. CSS / HTML: Define a map container
#map { height:400px; width:400px; border:1px solid grey; }
<div id='map'></div>
2. Create a custom picture layer
var pic_tileLayers = [ new GTileLayer(copyrightCollection , 0, 17)];
pic_tileLayers[0].getTileUrl = customGetTileURL;
pic_tileLayers[0].isPng = function() { return false; };
pic_tileLayers[0].getOpacity = function() { return 1.0; };
3. Define a new map type
var pic_customMap = new GMapType(pic_tileLayers, new
GMercatorProjection(4),'Pic',{maxResolution:3,
minResolution:0});
4. Create and initialise the custom map
map = new GMap2(map,{mapTypes:[pic_customMap]});
map.setCenter(new GLatLng(centreLat, centreLon),
initialZoom,pic_customMap);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
30
Custom Tile Layers: Implementation (2)
5. Display the correct tile (the clever bit)
function customGetTileURL(a,b) {
var c=Math.pow(2,b);
var d=a.x;
var e=a.y;
var f='t';
for(var g=0;g<b;g++){
c=c/2;
if(e<c){
if(d<c){f+='q'}
else{f+='r';d-=c}
}
else{
if(d<c){f+='t';e-=c}
else{f+='s';d-=c;e-=c}
}
}
return 'tiles/'+f+'.jpg'
}
Good news: The 3rd Party Google Maps Image Cutter software can be
used to automatically generate image tiles and writes this code for you
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
31
Flash API: Introduction
The Javascript API has limitations inherent to the platform
Painful to embed in Flash sites
Graphical/data streaming limitations
Solution: Flash Maps API
How does it work?
Lets you write code in Actionscript3, compile it against our interface library, and
output a SWF containing an interactive Google Map
SWF can be embedded on your web page, Google Earth, MySpace, etc
The Flash API has all the main functionality of the Javascript API
Google Confidential and Proprietary
32
Flash API: Examples (1)
1. Better/more Vector Graphics
Flash handles vector graphics natively
Example: Thematic Mapping
2. Rotatable maps
Map is rendered as a sprite, rotatable in Flash
Example: Spinning Map
3. Smoother video/animation
Flash animation is native and smooth
Example: Google Map Driving Simulator (Converted
from JS: Doubled frame-rate, halved CPU usage)
Google Confidential and Proprietary
33
3D Flash Maps
http://googlegeodevelopers.blogspot.com/2009/07/3d-perspective-in-maps-api-for-flash.html
Google Confidential and Proprietary
Flash API in 3D: Two lines of code...
1. Replace ‘Map’ with Map3D
2. Turn on perspective
Map3D.viewMode = View.VIEWMODE_PERSPECTIVE;
3. Add a navigation control
addControl(NavigationControl);
Google Confidential and Proprietary
35
Reverse Geocoding
We have offered geocoding of addresses for a long time
Standard geocoding converts an address into a latitude and longitude pair
But what happens when you want to find the address of a point on the map?
Solution: Reverse geocoding (new!)
Instead of an address, pass a lat/long to the GeoCoder
geocoder.getLocations(latlng, function(addresses) {
if(addresses.Status.code != 200) {
alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
}
else {
var result = addresses.Placemark[0];
map.openInfoWindow(latlng, result.address);
}
});
Example: MeetWays.com
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
36
Wikipedia and Panoramio Layers
In May, we added two new layers to Google Maps

Panoramio layer shows geo-coded user-submitted photos

Wikipedia layer plots geo-coded articles
You can add these layers to your API
implementation with just 2 lines of code
map.addOverlay(new GLayer("com.panoramio.all"));
map.addOverlay(new GLayer("org.wikipedia.en"));
 There are localised versions of the Wikipedia
layer available in many languages
Example Wikipedia and Panoramio implementation
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
37
Street View Service: Introduction
Street View provides panoramic 360 degree street-level views
in certain areas within the Google Maps coverage
Coverage
 Areas covered includes 70% of the USA, Canada, Australia, New Zealand,
United Kingdom, Czech Republic, France, Italy Netherlands, Portugal, Spain,
Switzerland, Japan, Taiwan, ...
 South Africa coming in 2010
Street View API
 Google Maps API provides a service for obtaining and manipulating Street
View imagery
 Street View uses Flash to display these interactive images
Google Confidential and Proprietary
38
Street View Service: Examples
Google Maps Directions (Print View)
(http://maps.google.com/)
 Printable directions show Street View
panorama of each junction, to aid
recognition
 Prior to printing, panoramas may be
rotated by the viewer as desired
Trulia Real Estate listings
(http://www.trulia.com/)
 Street View panorama shows exterior
view of properties for sale
 User can click arrows to ‘walk’ around
neighbourhood
Google Confidential and Proprietary
39
Street View Service: Adding SV to a page
1. CSS / HTML: Define a Street View container
#pano { height:200px; width:200px; border:1px solid grey; }
<div id='pano'></div>
2. Initialise panorama variables
location = new GLatLng(40.754501,-73.984358);
myPOV = { yaw:370, pitch:-20 };
svOpts = { latlng:location, pov:myPOV };
3. Create and initialise the panorama object
var myPano = new GStreetviewPanorama(document.getElementById('pano'));
myPano.setLocationAndPOV(location, svOpts);
4. Handle unsupported browsers
GEvent.addListener(myPano, 'error', handleNoFlash);
function handleNoFlash(errorCode) {
if (errorCode == 603) {
alert('Error: Flash is not supported by your browser');
return;
}
}
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
40
Street View Service: Updating from map clicks
1. Initialise panorama client variable
panoClient = new GStreetviewClient();
2. Grab coordinates of map clicks
GEvent.addListener(map, 'click', function(overlay, latlng) {
panoClient.getNearestPanorama(latlng, showPanoData);
});
3. Update Street View panorama
function showPanoData(panoData) {
myPano.setLocationAndPOV(panoData.location.latlng);
}
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
41
Earth API: Introduction
Google Earth is a powerful 3D mapping tool that, until this year, required
users to download a dedicated app
Requires a degree of technical expertise and suitable permissions
Could not be tightly integrated with web content
Solution: The Google Earth API allows Google Earth to be embedded in a
website, with no requirement to launch the app
How does it work?
Users download a plugin the first time they use (currently available only for
Windows; Mac and Linux versions coming)
If users do not have the plugin, implementations can gracefully degrade to a
2D Maps implementation
When to use?
Applications benefiting from a 3D geographic perspective
Option to integrate 3D buildings modelled in SketchUp
Google Confidential and Proprietary
42
Earth API: Examples
1) Ships
http://ships1.planetinaction.com/
Take the driving seat of a supertanker
Explore the world!
2) Monster Milktruck
http://www.google.com/earth/plugin/examples/milktruck/
3D driving game
Jump anywhere on the Earth’s surface
Google Confidential and Proprietary
43
Earth API: Adding a 3D map to a page
1. CSS / HTML: Define a map container
#map3d { height:400px; width:400px; border:1px solid grey; }
<div id='map3d'></div>
2. Use the Google AJAX API Loader
<script type='text/javascript'
src='http://www.google.com/jsapi?key=ABCDEFG'>
<script>google.load('earth', '1');</script>
3. Initialise the Earth container
function init() {
geocoder = new GClientGeocoder();
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(object) {
ge = object;
ge.getWindow().setVisibility(true);
}
function failureCB(object) {
alert('load failed');
}
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
44
Earth API: Setting the view (1)
1. Define view variables
var lat = 51.5;
var lng = 0;
var altitude = 100;
var tilt = 0;
var heading = 45;
var range = 1000;
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
45
Earth API: Setting the view (2)
2. Set the view
var la = ge.createLookAt('');
la.set(lng, lat, altitude,
ge.ALTITUDE_RELATIVE_TO_GROUND,
tilt, heading, range);
ge.getView().setAbstractView(la);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
46
Earth API: Tips and tricks
3D Maps can be combined with 2D maps, for graceful degradation if the
user does not have the plugin installed
1. Add a 3D map type
map.addMapType(G_SATELLITE_3D_MAP);
2. Obtain a pointer to the Earth instance
map.getEarthInstance(getEarthInstanceCB);
var ge;
function getEarthInstanceCB(object) {
ge = object;
}
3. Switch to 3D map type
map.setMapType(G_SATELLITE_3D_MAP);
Key:
Javascript
CSS
HTML
Google Confidential and Proprietary
47
Bringing it all together
Google Earth Driving Simulator
http://earth-api-samples.googlecode.com/svn/trunk/demos/drive-simulator/
 Directions
 Construct directions from point A to point B
 Google Earth API
 View route driven in 3D
 Set start / end points and speed
 Google Maps
 Track progress in 2D Maps pane
Google Confidential and Proprietary
48
Coming next....
Google Maps v3
 Looks similar to the existing version 2 of the Google Maps API - however,
much has changed under the hood
 Uses new MVC architecture to load fast, especially on mobile
 The initial launch has a smaller feature set than that available in the V2 API
 Beta available now and launches in 2010
Google Confidential and Proprietary
49
Have fun!
Lots more developer resources online...
 AJAX API Playground
 http://code.google.com/apis/ajax/playground/
 Geo Developers Blog
 http://googlegeodevelopers.blogspot.com/
 Google Code
 http://code.google.com/
Google Confidential and Proprietary
50
Download