Google Confidential and Proprietary 2
What’s New in Geo?
Nicola Ferioli
Customer Solutions Engineer
October, 2008
Google Confidential and Proprietary 3
Agenda
1. Maps API: The Crash Course
2. Cool (mostly) new features AJAX Search API
Static Maps API
Flash API
Earth API
Street View Service
Location Detection
Custom Tile Layers
3. Sharing Geo data between applications (using KML)
Google Confidential and Proprietary 4
Maps APIThe crash course
Google Confidential and Proprietary 5
Google Maps: Adding a map to your page
#map { height:400px; width:400px; border:1px solid grey; }
1. CSS / HTML: Define a map container
<div id='map'></div>
map.addControl(new GLargeMapControl());map.addControl(new GHierarchicalMapTypeControl());
4. Add controls
var lat = 51.49494; var lng = -0.14657; var initialzoom = 17;map.setCenter(new GLatLng(lat, lng),initialzoom);
5. Initialise the map
JavascriptKey: CSS HTML
var map = new GMap2(document.getElementById('map'));
3. Create the map
<script type='text/javascript' src='http://www.google.com/jsapi?key=ABCDEFG'><script>google.load('maps', '2');</script>
2. Use the Google AJAX API Loader
Google Confidential and Proprietary 6
Google Maps: A note on the AJAX loader
JavascriptKey: CSS HTML
<script type='text/javascript' src='http://www.google.com/jsapi?key=ABCDEFG'>
1. Loading the AJAX loader library
<script>google.load('maps', '2');</script>
2. Loading the Maps API
Loading the Maps API is a two step process:
The two step process means you can opt to load the Maps API only when an action is initiated by user
This is useful for embedding Maps in Google Gadget Ads, where the initial load limit is 50kb (the Maps API is substantially larger than this, whereas the AJAX loader is 4kb)
Google Confidential and Proprietary 7
Google Maps: Adding a marker
var marker = new GMarker(new GLatLng(lat, lon));
1. Initialise the marker
GEvent.addListener(marker, 'click', function() {marker.openInfoWindowHtml('<h1>LondonGoogleplex</h1><p>Welcome!</p>');
});
2. Make a bubble pop up when clicked
map.addOverlay(marker);
3. Display the marker
JavascriptKey: CSS HTML
Google Confidential and Proprietary 8
Google Maps: Adding a line
var latOffset = 0.001;var lngOffset = 0.001;
1. Initialise lat/lon offset from our marker (optional)
var line = new GPolyline([new GLatLng(lat, lng-lngOffset),new GLatLng(lat, lng+lngOffset)]);
2. Create the line
map.addOverlay(line);
3. Display the line
JavascriptKey: CSS HTML
Google Confidential and Proprietary 9
Google Maps: Adding a polygon
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);
1. Create the polygon and set line / fill properties
map.addOverlay(polygon);
2. Display the polygon
JavascriptKey: CSS HTML
Google Confidential and Proprietary 10
Google Maps: Geocoding an address
var address1 = '1 Strand, London';
1. Define the address to be geocoded
var geocoder = new GClientGeocoder();
2. Create the GClientGeocoder object
geocoder.getLatLng(address1, function(point) {map.setCenter(point,initialzoom);var marker = new GMarker(point);map.addOverlay(marker);
marker.openInfoWindowHtml('<h1>1Strand</h1><p>London</p>');
});
3. Geocode the address and place a marker
JavascriptKey: CSS HTML
Google Confidential and Proprietary 11
Google Maps: Displaying directions
gdir = new GDirections(map,directions);
3. Create the GDirections object
gdir.load('from: ' + address1 + ' to: ' + address2);
4. Compute and display the directions
JavascriptKey: CSS HTML
#directions { width:400px;}
1. CSS / HTML: Define a text directions container
<div id = 'directions'></div>
address2 = '76 Buckingham Palace Road, London'
2. Define the address(es) to be geocoded
Live Demo
Google Confidential and Proprietary 12
Cool (mostly) new featuresAJAX Search APIStatic Maps APIFlash APIEarth APIStreet View ServiceLocation DetectionCustom Tile Layers
Google Confidential and Proprietary 13
AJAX Search API: Introduction
Adding a search box to your Google Maps implementation used to be a convoluted processSearch terms had to be collected in a <form> and passed to MapsNo way to access local business results available from maps.google.com
The AJAX Search API simplifies the process and gives access to local business results
The AJAX Search API simplifies the process and gives access to local business results
Results can be shown in a menu… …or just on the map
Default implementation Compact implementation
Google Confidential and Proprietary 14
AJAX Search API: Implementation
1. Load AJAX Search API
var options = { resultList : document.getElementById('results') }; map.addControl(new google.maps.LocalSearch(options));
4. Tweak behaviour (e.g. send text results to container)
JavascriptKey: CSS HTML
map.addControl(new google.maps.LocalSearch());
3. Add a Local Search Control to your map
<script>google.load(search', ‘1');</script>
2. Load the Style Sheets
<style type='text/css'> @import url('http://www.google.com/uds/css/gsearch.css'); @import url('http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css');</style>
<div id='results'></div>
Google Confidential and Proprietary 15
Static Maps API: Introduction
The full Javascript Maps interface takes time to load Scripts to process Large images to download
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
Solution: The Static Maps API reduces load time by displaying a static image,rather than the full Javascript Maps interface
Solution: The Static Maps API reduces load time by displaying a static image,rather than the full Javascript Maps interface
The Static Maps API can be combined with the Javascript APIfor a better user experience
The Static Maps API can be combined with the Javascript APIfor a better user experience
Google Confidential and Proprietary 16
Static Maps API: Examples
1) Lonely Planet Mobile (http://m.lonelyplanet.com/)Displays static map of current user locationPlots 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 incidentsCollects input from mobile users
Google Confidential and Proprietary 17
Static Maps API: Implementation
Good news! Just add an <img> tag pointing to a well-crafted URLe.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 18
Static Maps API: Tips and tricks
The Static Maps API can be combined with the Javascript APIfor a better user experience
The Static Maps API can be combined with the Javascript APIfor 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 19
Flash API: Introduction
The Javascript API has limitations inherent to the platformPainful to embed in Flash sitesGraphical/data streaming limitations
How does it work?Lets you write code in Actionscript3, compile it against our interface library, and output a SWF containing an interactive Google MapSWF can be embedded on your web page, Google Earth, MySpace, etc
The Flash API has all the main functionality of the Javascript APIThe Flash API has all the main functionality of the Javascript API
Solution: Flash Maps APISolution: Flash Maps API
Google Confidential and Proprietary 20
Flash API: Examples (1)
1. Integration into Flash/Flex sitesSome sites are already built entirely in Flash/Flex, and integrating a JS API can be painfulExample: Navx (UI already in Flex – integrated Flash API in under a week)
2. Smoother video/animationFlash animation is native and smoothExample: Google Map Driving Simulator (Converted from JS: Doubled frame-rate, halved CPU usage)
3. Better/more Vector GraphicsFlash handles vector graphics nativelyExample: Thematic Mapping
Google Confidential and Proprietary 21
Flash API: Examples (2)
4. Better binary and real-time data streamingFlash can make raw socket connections so that a continuous stream of data can be readExample: Collaborative Chat Rooms
5. Rotatable mapsMap is rendered as a sprite, rotatable in FlashExample: Spinning Map
6. More embeddableFor mostly security related reasons, there are places Flash can be embedded where JS cannotExamples: MySpace Profiles, Google Earth
Google Confidential and Proprietary 22
Earth API: Introduction
Google Earth is a powerful 3D mapping tool that, until this year, required users to download a dedicated appRequires a degree of technical expertise and suitable permissionsCould not be tightly integrated with web content
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 perspectiveOption to integrate 3D buildings modelled in SketchUp
Solution: The Google Earth API allows Google Earth to be embedded in a website, with no requirement to launch the app
Solution: The Google Earth API allows Google Earth to be embedded in a website, with no requirement to launch the app
Google Confidential and Proprietary 23
Earth API: Examples
1) Singapore 3D Explorerhttp://www.earthsg.com/3dsingapore/
Explore Singapore Grand Prix trackBuildings and track modelled in 3DTextual information on landmarks
2) Monster Milktruckhttp://www.google.com/earth/plugin/examples/milktruck/
3D driving gameJump anywhere on the Earth’s surface
Google Confidential and Proprietary
Earth API: Adding a 3D map to a page
<script type='text/javascript' src='http://www.google.com/jsapi?key=ABCDEFG'><script>google.load('earth', '1');</script>
2. Use the Google AJAX API Loader
#map3d { height:400px; width:400px; border:1px solid grey; }
1. CSS / HTML: Define a map container
<div id='map3d'></div>
JavascriptKey: CSS
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');}
3. Initialise the Earth container
HTML 24
Google Confidential and Proprietary
Earth API: Setting the view (1)
var lat = 51.5;var lng = 0;var altitude = 100;var tilt = 0;var heading = 45;var range = 1000;
1. Define view variables
JavascriptKey: CSS HTML 25
Google Confidential and Proprietary
Earth API: Setting the view (2)
var la = ge.createLookAt(''); la.set(lng, lat, altitude, ge.ALTITUDE_RELATIVE_TO_GROUND,
tilt, heading, range);ge.getView().setAbstractView(la);
2. Set the view
JavascriptKey: CSS HTML 26
Google Confidential and Proprietary 27
Earth API: Tips and tricks
map.addMapType(G_SATELLITE_3D_MAP);
1. Add a 3D map type
map.getEarthInstance(getEarthInstanceCB);var ge;function getEarthInstanceCB(object) { ge = object;}
2. Obtain a pointer to the Earth instance
map.setMapType(G_SATELLITE_3D_MAP);
3. Switch to 3D map type
3D Maps can be combined with 2D maps, for graceful degradation if the user does not have the plugin installed
3D Maps can be combined with 2D maps, for graceful degradation if the user does not have the plugin installed
JavascriptKey: CSS HTML
Google Confidential and Proprietary 28
Street View Service: Introduction
Coverage Areas covered include most US cities Coverage will be expanded in future
Street View API
Google Maps API now provides a service for obtaining and manipulating
Street View imagery Plugin uses the Flash API to display these interactive images
Street View provides panoramic 360 degree street-level viewsin certain areas within the Google Maps coverage
Street View provides panoramic 360 degree street-level viewsin certain areas within the Google Maps coverage
Google Confidential and Proprietary 29
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
Street View Service: Adding SV to a page
location = new GLatLng(40.754501,-73.984358);myPOV = { yaw:370, pitch:-20 };svOpts = { latlng:location, pov:myPOV };
2. Initialise panorama variables
var myPano = new GStreetviewPanorama(document.getElementById('pano'));myPano.setLocationAndPOV(location, svOpts);
3. Create and initialise the panorama object
JavascriptKey: CSS HTML
GEvent.addListener(myPano, 'error', handleNoFlash);function handleNoFlash(errorCode) { if (errorCode == 603) { alert('Error: Flash is not supported by your browser'); return; }}
4. Handle unsupported browsers
#pano { height:200px; width:200px; border:1px solid grey; }
1. CSS / HTML: Define a Street View container
<div id='pano'></div>
30
Google Confidential and Proprietary
Street View Service: Updating from map clicks
panoClient = new GStreetviewClient();
1. Initialise panorama client variable
GEvent.addListener(map, 'click', function(overlay, latlng) { panoClient.getNearestPanorama(latlng, showPanoData);});
2. Grab coordinates of map clicks
function showPanoData(panoData) { myPano.setLocationAndPOV(panoData.location.latlng);}
3. Update Street View panorama
JavascriptKey: CSS HTML 31
Google Confidential and Proprietary
Street View Service: Panoclient response location: { latlng: GLatLng('42.345566, -71.098354') pov: { yaw: '370.64659986187695' pitch: '-20' zoom: '1' } description: 'Yawkey Way' panoId: '-KNGDaZvSQjMqug7ISM_CA' }
copyright: '© 2008 Google'
links:[ { yaw: '0' description: 'Yawkey Way' panoId: 'S142iWXa_4Fi7L7d8HKhuQ' }, { yaw: '0' description: 'Yawkey Way' panoId: '2vFI79AjOpHTAYJSCKquFg' } ]
Current Street View object:Lat / LongDefault yaw, pitch and zoomDescriptionID
Copyright
Next / previous Street View objects:Default yawDescriptionID
e.g. To access lat/lon data stored in panoData variable: panoData.location.latlnge.g. To access lat/lon data stored in panoData variable: panoData.location.latlng
JavascriptKey: CSS HTML 32
Google Confidential and Proprietary 33
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
How does it work? 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
Solution: Automatic location detection in the AJAX APISolution: Automatic location detection in the AJAX API
Google Confidential and Proprietary 34
Location Detection: Implementation
map.setCenter(lat,lng);
3. Centre the map
JavascriptKey: CSS HTML
if (google.loader.ClientLocation) {var lat = google.loader.ClientLocation.latitude;var lng = google.loader.ClientLocation.longitude;
}
1. Check if ClientLocation object is defined
else {var lat = 51.0;var lng = 0.0;
}
2. If not, set lat/long manually
ClientLocation.address.cityClientLocation.address.countryClientLocation.address.country_codeClientLocation.address.region
You can also access:
Google Confidential and Proprietary 35
Custom Tile Layers: Introduction
All non-geocoding functionality can be used with custom tile layers Map controls Markers Bubbles Mouse zoom/pan etc…
Multiple rescaled images are required, corresponding to map zoom levels Each image must be divided into a grid of square tiles
The Google Maps interface can be used to browse multi-resolution images by defining a custom map type
The Google Maps interface can be used to browse multi-resolution images by defining a custom map type
Good news: The 3rd Party Google Maps Image Cutter software can be used to automatically generate rescaled images and tiles
Good news: The 3rd Party Google Maps Image Cutter software can be used to automatically generate rescaled images and tiles
Google Confidential and Proprietary 36
Custom Tile Layers: Example
Kremer Collection Photography (www.thekremercollection.com)
Map navigator and zoom level control
Content copyright notice
Orientationnavigator
Google Confidential and Proprietary
Custom Tile Layers: Implementation (1)
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; };
2. Create a custom picture layer
JavascriptKey: CSS
var pic_customMap = new GMapType(pic_tileLayers, newGMercatorProjection(4),'Pic',{maxResolution:3,
minResolution:0});
3. Define a new map type
HTML
map = new GMap2(map,{mapTypes:[pic_customMap]});map.setCenter(new GLatLng(centreLat, centreLon), initialZoom,pic_customMap);
4. Create and initialise the custom map
#map { height:400px; width:400px; border:1px solid grey; }
1. CSS / HTML: Define a map container
<div id='map'></div>
37
Google Confidential and Proprietary
Custom Tile Layers: Implementation (2)
JavascriptKey: CSS HTML
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' }
5. Display the correct tile (the clever bit)
Good news: The Image Cutter software generates this code for you!Good news: The Image Cutter software generates this code for you!
38
Google Confidential and Proprietary 39
Sharing Geo data between applicationsUsing KML
Google Confidential and Proprietary 40
KML: Introduction
Keyhole Markup Language (KML) is an XML-based language for expressing geographic annotation and visualizationDeveloped 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 viewsEach 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
KML: Placemarks
<?xml version='1.0' encoding='UTF-8'?><kml xmlns='http://www.opengis.net/kml/2.2'>
<Placemark>
</kml>
Headers
In this example, we create a placemark with a name, description and altitudeIn this example, we create a placemark with a name, description and altitude
<name>Simple placemark</name>
</Placemark>
<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>
<Point><coordinates>-122.0.4,0</coordinates>
</Point>
Placemark definition
Placemark name
Placemark HTML description
Placemark lat/long/altitude
JavascriptKey: CSS HTML 41
Google Confidential and Proprietary
<LineString>
KML: Paths
<Placemark>
Now we create a path at altitude, extended down to the groundNow we create a path at altitude, extended down to the ground
<name>Extruded path</name>
</Placemark>
<description>Path extended to the ground</description>
<coordinates> -112.2550785337791,36.07954952145647,2357 -112.2549277039738,36.08117083492122,2357 -112.2552505069063,36.08260761307279,2357 -112.2564540158376,36.08395660588506,2357</coordinates>
Placemark definition
Placemark name
Line definition
<extrude>1</extrude>
</LineString>
<tesselate>1</tesselate>
Placemark name
Extend down to the ground
Break into smaller chunks
Coordinate lat/long
JavascriptKey: CSS HTML 42
Google Confidential and Proprietary
KML: Network links
Folder definition
Network links allow content to be updated, based on data/algorithms hosted elsewhereNetwork links allow content to be updated, based on data/algorithms hosted elsewhere
<Folder>
<name>Network Links</name>
</Folder>
JavascriptKey: CSS HTML 43
<description>Network Links Example</description>
<NetworkLink>
<name>Random Placemark</name>
<description>A simple server-side script that generates a new random placemark on each call</description>
<Link>
<href>randomPlacemark.py</href>
</Link>
</NetworkLink>
Folder name
Folder description
Network Link definition
Network Link name
Network Link description
Link definition
Link URL (generates KML)
Google Confidential and Proprietary
KML: Styles
Style definition
Finally, we define a style and attach it to a placemarkFinally, we define a style and attach it to a placemark
Line style definition
<Style id='yellowLineGreenPoly'>
<LineStyle>
<color>7f00ffff</color><width>4</width>
</LineStyle>
<Placemark>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<styleUrl>#yellowLineGreenPoly</styleUrl>
…
<Placemark>
Polygon style definition
Placemark definition
Link to style
Placemark details
JavascriptKey: CSS HTML 44
Google Confidential and Proprietary 45
KML: What to do with it
1. Display it in Google Maps
KML can be displayed in Google Maps, Earth and Static Maps and other compatible geo applications
KML can be displayed in Google Maps, Earth and Static Maps and other compatible geo applications
var kml = new GGeoXml('http://mydomain.com/myfile.kml');map.addOverlay(kml)
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
JavascriptKey: CSS HTML
Google Confidential and Proprietary 46
KML: Submit it to Google!
1. Create the KML content and include attribution tags
KML can be submitted to the Google index, making it discoverable from google.com and maps.google.com
KML can be submitted to the Google index, making it discoverable from google.com and maps.google.com
<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
JavascriptKey: CSS HTML
Google Confidential and Proprietary 47
Bringing it all together
Google Earth Driving Simulatorhttp://earth-api-samples.googlecode.com/svn/trunk/demos/drive-simulator/
Directions Construct directions from point A to point B
Google Earth Plugin View route driven in 3D Set start / end points and speed
Google Maps Track progress in 2D Maps pane
Google Confidential and Proprietary
Learn more
http://code.google.com