SlideShare una empresa de Scribd logo
1 de 100
Google AJAX APIs
Implement rich, dynamic web sites entirely in JavaScript and HTML.

Eric 2010
Outline
• Self-Introduction
• Google APIs Introduction
• Google Ajax Search API
• Google Maps API
• Google Chart API
• Google Data API
Self Introduction
Self Introduction
• Eric
Google APIs Introduction
Google APIs Introduction
• 8 category APIs
• Over 80 APIs we can use
• http://code.google.com/
Google Code Web Site
• US site vs. Taiwan site
Developer Resources
• Google Code Website
   • http://code.google.com/
• Code Playground
   • http://code.google.com/apis/ajax/playground/
• Firefox & Firebug
   • http://moztw.org/
• Google Code Blog
   • http://googlecode.blogspot.com/
Some Interesting APIs #1
• Google Account Authentication
 ‧ Get access into desktop or mobile applications.
• Google AJAX Feed API
 ‧ Get access into desktop or mobile applications.
• Google AJAX Language API
 ‧ Easily translate and detect multiple languages using JavaScript.
• Android
 ‧ Build mobile apps for mobile devices.
• Google App Engine
 ‧ Run your web applications on Google's infrastructure.
• Google Apps
 ‧ Extend Google Apps, integrate or build new apps.
• Blogger Data API
 ‧ Enable your apps to view and update Blogger content.
Some Interesting APIs #2
• Google Calendar APIs and Tools
 ‧ Create and manage events, calendars
• Google Chrome Extensions
 ‧ Modify and enhance the functionality of Google Chrome
• Google Earth API
 ‧ Embed Google Earth into your web page.
• KML
 ‧ Create and share content with Google Earth, Maps
• Google Libraries API
 ‧ Load open source JavaScript libraries.
• reCAPTCHA
 ‧ An anti-bot service.
• YouTube APIs
 ‧ Integrate YouTube videos into your website or application.
WHAT LANGUAGES WE USE
IN THIS OFFERING
• JavaScript
• HTML
Google AJAX Search API
Google AJAX Search API Intro

• The Google AJAX Search API lets you put Google
Search in your web pages with JavaScript.

• Getting Start
 ‧ Get Google AJAX Search API Key and start coding
 ‧ Or Generate cut-and-paste HTML, it’s an easy way

• Web Resources
  ‧ http://code.google.com/apis/ajaxsearch/
  ‧ http://groups-beta.google.com/group/Google-AJAX-Search-API
  ‧ http://code.google.com/apis/ajaxsearch/samples.html
Google AJAX Search API Wizards #1

• http://code.google.com/apis/ajaxsearch/wizards.html
Google AJAX Search API Wizards #2
• For Example : Video Search Wizard
• http://www.google.com/uds/solutions/wizards/videosearch.html
• Only 4 Steps
   • Customize it
   • Tell Google about your web site
   • Generate code for your web page
   • Paste code in your web page
"Hello World" of Google AJAX Search API #1

• Sign-up for an AJAX Search API Key
"Hello World" of Google AJAX Search API #2

• The "Hello, World" of Google AJAX Search API
• Sample Code
   • http://www.google.com/uds/samples/apidocs/helloworld.html

• Using the Google AJAX API Loader

<script type="text/javascript"
src="http://www.google.com/jsapi?key=ABCDEFG"></script>

<script type="text/javascript">
 google.load("search", "1");
</script>
"Hello World" of Google AJAX Search API #3
• Call this function when the page has been loaded
   function initialize() {
     var searchControl = new google.search.SearchControl();
     searchControl.addSearcher(new google.search.WebSearch());
     searchControl.addSearcher(new google.search.NewsSearch());
     searchControl.draw(document.getElementById("searchcontrol"));
   }

• Execute Search function
  searchControl.execute("VW GTI");

• Use google.setOnLoadCallback to register the specified
handler function
  google.setOnLoadCallback(initialize);

• Put <div> in HTML
  <div id="searchcontrol">Loading</div>
Google AJAX Search API Overview
• The Search Control

   This provides the user interface and coordination over a number of
   searcher objects

• Searchers

   It defines the interface that all searcher services must implement

• GResult

   the search results produced by the searcher objects

• Searcher Options

   This class configures the behavior of searcher objects
Google AJAX Search API Overview #sample code1
// create a searcher object
var sc = new google.search.SearchControl();

// add one or more searchers, specifying options as needed
var options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPA
ND_MODE_OPEN);
sc.addSearcher(new google.search.WebSearch(), options);
...

// activate the search control by calling it's .draw() method
sc.draw(document.getElementById("myDiv"));
Google AJAX Search API Overview #sample code2
<!-- A collection of web search results in the search control -->
<div class="gsc-results gsc-webResult">

 <!-- A single web result in the search control -->
 <div class="gsc-result gsc-webResult">

   <!-- A single web result, full structure defined below -->
   <div class="gs-result gs-webResult"></div>
 </div>
 ...
</div>

<!-- Similar pattern for local, blog, etc. -->
<div class="gsc-results gsc-localResult"></div>
<div class="gsc-results gsc-blogResult"></div>
The Search Control
• google.search.SearchControl
• google.search.SearchForm

• google.search.CustomSearchControl
• GSmapSearchControl

• GSvideoBar
• GSnewsBar
• GSvideoSearchControl
• GSbookBar
• GSblogBar
google.search.SearchControl #1
• An instance of google.search.SearchControl represents a
single search control on a page

•是用來裝載搜尋功能的控制容器,所有搜尋功能的物件
都必須放入這個容器中才能運作。

•要建立google.search.SearchControl物件,可以使用下列
範例語法
var searchControl = new google.search.SearchControl();
google.search.SearchControl #2
- addSearcher(searcher, opt_options)

•這個函式可以將搜尋器加入搜尋控制容器中。搜尋控制
容器在最後執行搜尋動作的階段,會針對它所擁有的搜
尋器進行相對應的搜尋與顯示搜尋結果的動作

• searcher – 指定搜尋器的種類

• opt_options – 非必填引數。這個引數可以針對搜尋器進
行外觀與行為的細部設定
google.search.SearchControl #3
- draw(element, GdrawOptions)

•本函式會為每個加入搜尋控制容器的搜索器進行搜尋介
面繪製的動作。只有在所有搜索器都已加入搜索控制容
器後,才可以呼叫此函式。

• element – HTML區塊元素。我們可以將搜尋控制容器放
置到指定的HTML區塊元素之中。通常HTML區塊元素是
指HTML中的<div>元素。

• GdrawOptions – 非必填的引數。這個引數可以用來設定
搜尋結果的顯示外觀。
google.search.SearchControl #4
- setTimeoutInterval(timeoutInterval)

•當我們利用draw函式中的Gdrawoptions引數來自訂搜尋
輸入欄位時,就可以使用setTimeoutInterval這個函式。這
個函式可以讓我們設定執行搜尋的時間間隔,每當使用
者在搜索輸入欄位中鍵入搜尋關鍵字時,就會有計時器
依據這個時間間隔開始進行倒數計時。當倒數結束,就
會依據搜尋欄位中的關鍵字開始進行搜尋動作。

timeoutInterval可填入之有效值                       時間間隔
google.search.SearchControl.TIMEOUT_SHORT    350ms


google.search.SearchControl.TIMEOUT_MEDIUM   500ms


google.search.SearchControl.TIMEOUT_LONG     700ms
google.search.SearchControl #5
- execute(str)

•本函式可以讓搜尋控制容器中所有的搜尋器依照所傳入
的搜尋關鍵字進行搜尋的動作。

• str – 搜尋關鍵字。
google.search.SearchControl #6
 - setOnKeepCallback(object, method, opt_keepLabel)

•本函式可以讓我們設定緊跟在搜尋結果後面的連結,以
及按下此連結時會被呼叫的函式。當使用者點擊該連結
後,會將該筆的搜尋結果物件傳送給我們所呼叫的函式。
透過這種方式,我們就可以對搜尋結果進行更進一步的
處理。
• object – 要呼叫函式所屬的物件名稱。
• method – 要呼叫的函式名稱。
• opt_keepLabel – 功能按鈕的顯示樣式。
屬性                                               說明
google.search.SearchControl.KEEP_LABEL_SAVE      「保持」連結樣式
google.search.SearchControl.KEEP_LABEL_INCLUDE   「包括」連結樣式
google.search.SearchControl.KEEP_LABEL_COPY      「複製」連結樣式
google.search.SearchControl.KEEP_LABEL_BLANK     空白連結樣式
其他任意文字                                           顯示該文字連結
google.search.SearchControl #7
- clearAllResults()

•本函式可以清除目前搜尋控制容器中的所有搜尋結果。
google.search.SearchControl #8
- setLinkTarget(linkTarget)

•本函式指定當使用者點擊搜尋結果連結時,在哪一個網
頁框架顯示該連結網頁。

• linkTarget – 設定點擊搜尋結果時,在哪一個網頁框架
顯示該連結網頁。
google.search.SearchControl #9
- setSearchCompleteCallback(object, method)

•我們可以透過setSearchCompleteCallback設定在搜尋動作
完成時所呼叫的函式。要注意的是,搜尋控制容器中每
一個搜尋器完成搜尋的時候就會執行一次要被呼叫的函
式。舉例來說,如果搜尋控制容器中的搜尋器有兩個,
該函式在搜尋動作完成後就會被執行兩次。

• object - 要呼叫函式所屬的物件名稱。
• method -要呼叫的函式名稱。
google.search.SearchControl #10
- setSearchStartingCallback(object, method)

•我們可以透過setSearchStartingCallback設定在搜尋動作
開始時所呼叫的函式。要注意的是,搜尋控制容器中每
一個搜尋器開始搜尋的時候就會執行一次要被呼叫的函
式。舉例來說,如果控制元件中的搜尋器有兩個,該函
式在搜尋動作開始時後就會被執行兩次。

• object - 要呼叫函式所屬的物件名稱。
• method -要呼叫的函式名稱。
google.search.SearchControl #11
- setNoResultsString(str)

•我們可以使用本函式設定當搜尋不到結果時,網頁所顯
示的文字。

• str - 當搜尋不到結果時,網頁所顯示的文字。
google.search.SearchForm #1
• The google.search.SearchForm object is a light weight
object that is designed for exactly this use case. It provides
applications with a text input element, a search button, an
optional clear button, as well as all standard branding.
•
•要建立google.search.SearchForm物件,可以使用下列範
例語法
var searchForm = new google.search.SearchForm(enableClear, element);

• enableClear – 這個引數為 ture 時,搜索輸入欄位就會包
含一個清除搜尋結果的按鈕,否則將不會有清除搜尋結
果的按鈕。
• element – HTML Element。
google.search.SearchForm #2
- setOnSubmitCallback(object, method)

• setOnSubmitCallback可以讓我們設定點選搜尋按鈕後所
呼叫的物件與函式,此外搜尋輸入欄位的值也會被傳遞
到要被呼叫的函式中。

• object - 要呼叫函式所屬的物件名稱。
• method -要呼叫的函式名稱。
google.search.SearchForm #3
- setOnClearCallback(object, method)

•本函式將會設定按下搜索輸入欄位的「清除」按鈕時被
呼叫的物件與函式。如果在建立google.search.SearchForm
物件時,沒有建立清除搜尋結果的按鈕,則呼叫此函式
時會發生錯誤。此外,搜尋輸入欄位的值也會被傳遞到
要被呼叫的函式中。

• object - 要呼叫函式所屬的物件名稱。
• method -要呼叫的函式名稱。
google.search.SearchForm #4
- execute(query)

•利用execute函式,可以讓搜尋器依照所傳入的搜尋關鍵
字進行搜尋的動作。

• query - 執行搜尋時所使用的關鍵字。
Searchers #1
Searchers #2
• google.search.WebSearch

var searcher = new google.search.WebSearch();

• google.search.LocalSearch

var searcher = new google.search.LocalSearch();

• google.search.VideoSearch
var searcher = new google.search.VideoSearch();

• google.search.BlogSearch
var searcher = new google.search.BlogSearch();
Searchers #3
• google.search.NewsSearch

var searcher = new google.search.NewsSearch();

• google.search.ImageSearch

var searcher = new google.search.ImageSearch();

• google.search.BookSearch
var searcher = new google.search.BookSearch();

• google.search.PatentSearch
var searcher = new google.search.PatentSearch();
GResult #1
• Result objects are produced using a JSON encoding of
server search requests.

• 當我們透過搜尋器進行搜尋動作後,除了會在指定的網
頁元素位置上顯示搜尋結果外,也會根據搜尋器的種類
回傳不同的搜尋結果物件。瞭解搜尋結果物件的屬性,
可以讓我們對搜尋結果物件進行更進一步的處理
GResult #2
• Result objects are produced using a JSON encoding of
server search requests.

• 當我們透過搜尋器進行搜尋動作後,除了會在指定的網
頁元素位置上顯示搜尋結果外,也會根據搜尋器的種類
回傳不同的搜尋結果物件。瞭解搜尋結果物件的屬性,
可以讓我們對搜尋結果物件進行更進一步的處理
Searcher Options
• When adding a searcher to the search control, the
GsearcherOptionsgoogle.search.SearcherOptions object may
be specified.
// create a searcher options object
// set up for open expansion mode
// load a searcher with these options
var options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MOD
E_OPEN);
searchControl.addSearcher(new google.search.WebSearch(), options);
DrawOptions Options
• When asking a search control to draw, you must specify a
container for the control to draw within.
• In addition to this required parameter, the search
control's .draw() method also accepts an optional
google.search.DrawOptions object.
// create a drawOptions object
var drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MO
DE_TABBED);
searchControl.draw(element, drawOptions);
Google Maps API
Google Maps API Family
• Google Maps has a wide array of APIs that let you embed
the robust functionality and everyday usefulness of Google
Maps into your own website and applications
Google Maps JavaScript API V3
• V3: The Solution for Maps Applications for both the
Desktop and Mobile Devices

• The version 3 of the Google Maps API will look similar to
the existing version 2 of the Google Maps API.

• Who uses Maps API:
  • Yelp: http://www.youtube.com/watch?v=jWmLCpE_nwg
  • 地圖日記

• Web Resources
  • http://groups.google.com/group/google-maps-js-api-v3
  • http://code.google.com/apis/maps/documentation/javascript/
"Hello World" of Google Maps V3 #1

• Sample Code URL
 • http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html


• Declaring Your Application as HTML5

  <!DOCTYPE html>

• 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>
"Hello World" of Google Maps V3 #2

• Map DOM Elements
<div id="map_canvas" style="width: 100%; height: 100%"></div>


• Map Options

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

• Create instance
var map = new
google.maps.Map(document.getElementById("map_canvas"), myOptions);
Geolocation
• Geolocation refers to the identification of the geographic
location of a user or computing device via a variety of data
collecton mechanisms.

• Newer browsers are starting to support the W3C Geolocation
standard.

// Try W3C Geolocation method (Preferred)
  if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
     initialLocation = new
google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    ……
    });}
Developing for Mobile Devices
• You can detect iPhone and Android devices by inspecting the
navigator.userAgent
function detectBrowser() {
 var useragent = navigator.userAgent;
 var mapdiv = document.getElementById("map_canvas");

    if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
      mapdiv.style.width = '100%';
      mapdiv.style.height = '100%';
    } else {
      mapdiv.style.width = '600px';
      mapdiv.style.height = '800px';
    }
}
Localization in the V3 Maps API
• Language Localization

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

• Region Localization
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&region=GB">
Base objects - LatLng
• LatLng is a point in geographical coordinates, latitude and longitude.

  var latlng = new google.maps.LatLng(60, 105);


Methods                        Return Value       Description
equals(other:LatLng)           boolean            Comparison function.
                                                  Returns the latitude in
lat()                          number
                                                  degrees.
                                                  Returns the longitude in
lng()                          number
                                                  degrees.
                                                  Converts to string
toString()                     string
                                                  representation.
                                                  Returns a string of the form
toUrlValue()                   string
                                                  "lat,lng" for this LatLng.
Base objects – LatLngBounds#1
  • A LatLngBounds instance represents a rectangle in geographical
  coordinates.

     var c = new google.maps.LatLngBounds(latlngA, latlngB);
Methods                          Return Value              Description
                                                           Returns true if the given lat/lng is in
contains(latLng:LatLng)          boolean
                                                           this bounds.
                                                           Returns true if this bounds
equals(other:LatLngBounds)       boolean                   approximately equals the given
                                                           bounds.
                                                           Extends this bounds to contain the
extend(point:LatLng)             LatLngBounds
                                                           given point.
                                                           Computes the center of this
getCenter()                      LatLng
                                                           LatLngBounds
                                                           Returns the north-east corner of this
getNorthEast()                   LatLng
                                                           bounds.
                                                           Returns the south-west corner of this
getSouthWest()                   LatLng
                                                           bounds.
                                                           Returns true if this bounds shares any
intersects(other:LatLngBounds)   boolean
                                                           points with this bounds.
isEmpty()                        boolean                   Returns if the bounds are empty.
Base objects – LatLngBounds#2

                                               Converts the given map bounds to a
toSpan()                        LatLng
                                               lat/lng span.
toString()                      string         Converts to string.
                                               Returns a string of the form
                                               "lat_lo,lng_lo,lat_hi,lng_hi" for this
                                               bounds, where "lo" corresponds to the
toUrlValue(precision?:number)   string
                                               southwest corner of the bounding box,
                                               while "hi" corresponds to the
                                               northeast corner of that box.
                                               Extends this bounds to contain the
union(other:LatLngBounds)       LatLngBounds
                                               union of this and the given bounds.
google.maps.Map
• Language Localization

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

• Some Functions
 setCenter(latlng:LatLng)
 setMapTypeId(mapTypeId:MapTypeId)
 setOptions(options:MapOptions)
 setZoom(zoom:number)
 getMapTypeId()
 getZoom()
Google Maps Javascript API V3 Controls
• Navigation control
• Scale control
• MapType control

• You don't access or modify controls directly. Instead, you
modify the map's MapOptions fields which affect the visibility
and presentation of controls. You can adjust control presentation
upon instantiating your map (with appropriate MapOptions) or
modify a map dynamically by calling setOptions() to change the
map's options.
The Default Control Set

Control      Large Screens    Small Screens     iPhone        Android

             Large
                              Small Mini-
             Pan/Zoom for
                              Zoom for sizes                  "Android"
Navigation   sizes larger                       Not present
                              smaller than                    control
             than
                              400x350px
             400x350px
             Horizontal Bar   Dropdown for
                                                Same as       Same as
             for screens      screens smaller
MapType                                         Large/Small   Large/Small
             larger than      than 320px
                                                Screens       Screens
             320px wide       wide
Scale        Not present      Not present       Not present   Not present
Disabling the Default UI
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
{
    navigationControl: boolean,
    mapTypeControl: boolean,
    scaleControl: boolean
}

function initialize() {
  var myOptions = {
    zoom: 4,
    center: new google.maps.LatLng(-33, 151),
    navigationControl: true,
    mapTypeControl : true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);
}
Control Options
• Navigation control
  • google.maps.NavigationControlStyle.SMALL
  • google.maps.NavigationControlStyle.ZOOM_PAN
  • google.maps.NavigationControlStyle.ANDROID
  • google.maps.NavigationControlStyle.DEFAULT

• MapType control
  • google.maps.MapTypeControlStyle.HORIZONTAL_BAR
  • google.maps.MapTypeControlStyle.DROPDOWN_MENU
  • google.maps.MapTypeControlStyle.DEFAULT
Control Positioning
function initialize() {
  var myOptions = {
    zoom: 12,
    center: new google.maps.LatLng(-28.643387, 153.612224),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true,
    mapTypeControlOptions: {
       style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
       position: google.maps.ControlPosition.BOTTOM
    },
    navigationControl: true,
    navigationControlOptions: {
       style: google.maps.NavigationControlStyle.ZOOM_PAN,
       position: google.maps.ControlPosition.TOP_RIGHT
    },
    scaleControl: true,
    scaleControlOptions: {
       position: google.maps.ControlPosition.TOP_LEFT
    }
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);
}
Google Maps Javascript API V3 Events #1
• UI Events            • Other Events
  •   click              •   drag
  •   dblclick           •   dragend
  •   mouseup            •   dragstart
  •   mousedown          •   maptypeid_changed
  •   mouseover          •   rightclick
  •   mouseout

• Map Events
  •   zoom_changed
  •   center_changed
  •   bounds_changed
  •   mousedown
  •   mouseover
  •   mouseout
Google Maps Javascript API V3 Events #2
var marker = new google.maps.Marker({
   position: myLatlng,
   map: map,
   title:"Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
 map.setZoom(8);
});
Google Maps Javascript API V3 Events #3
• Accessing Arguments in UI Events
   • MouseEvent

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



Properties              Type                      Description
                                                  The latitude/longitude
                                                  that was below the
latLng                  LatLng
                                                  cursor when the event
                                                  occurred.
Google Maps JavaScript API V3 Overlays #1
• Overlays are objects on the map that are tied to
latitude/longitude coordinates, so they move when you drag or
zoom the map. Overlays reflect objects that you "add" to the
map to designate points, lines, areas, or collections of objects.

• several types of overlays:
  • markers
  • polylines
  • overlay map types
  • info window
  • custom overlays
Google Maps JavaScript API V3 Overlays #2
• Adding Overlays

 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,
    title:"Hello World!"
 });

 // To add the marker to the map, call setMap();
 marker.setMap(map);
Google Maps JavaScript API V3 Overlays #3
• Removing Overlays
• http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
     markersArray[i].setMap(null);
    } }}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
     markersArray[i].setMap(map);
    } }}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }}
Google Maps JavaScript API V3 Overlays #4
• Markers
  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!"
 });
Google Maps JavaScript API V3 Overlays #5
• Simple Icons
  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
  var marker = new google.maps.Marker({
     position: myLatLng,
     map: map,
     shadow: shadow,
     icon: image,
     shape: shape,
     title: beach[0],
     zIndex: beach[3]
  });
Google Maps JavaScript API V3 Overlays #6
• Polylines

   • A polyline supports the following stroke styles:
      • strokeColor
      • strokeOpacity
      • strokeWeight

 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);
Google Maps JavaScript API V3 Overlays #7
• Polygons

    • A polygons supports the ploylines stroke styles and fill styles:
       • fillColor
       • fillOpacity
 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);
Google Maps JavaScript API V3 Overlays #8
• Ground
var oldmap = new google.maps.GroundOverlay(
  "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg",
  imageBounds);
oldmap.setMap(map);
Google Maps JavaScript API V3 Overlays #9
• InfoWindows
      • Methods
Methods                           Return Value   Description
close()                           None           Closes this InfoWindow
getContent()                      string|Node
getPosition()                     LatLng
getZIndex()                       number
open(map:Map|StreetViewPanora
                                  None
ma, anchor?:MVCObject)
setContent(content:string|Node)   None

• InfoWindow options
  •    content
  •    pixelOffset
  •    position
  •    maxWidth
Google Maps JavaScript API V3 Overlays #10
• KML and GeoRSS Layers
   • The Google Maps API supports the KML and GeoRSS data formats for
displaying geographic information. These data formats are displayed on a
map using a KmlLayer object, whose constructor takes the URL of a publicly
accessible KML or GeoRSS file.
Google Maps JavaScript API V3 Overlays #11
• The Traffic Layer
• The Bicycling Layer

  • http://gmaps-samples.googlecode.com/svn/trunk/mapcoverage_filtered.html
Google Maps JavaScript API V3 Services #1
• 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.

• 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.
Google Maps JavaScript API V3 Services #2
• The GeocodeRequest object literal contains the following fields:
• address: string (*)
• latLng: LatLng (*)
• bounds: LatLngBound
• region: string

• Geocoding Results
   results[]: {
    types[]: string,
    formatted_address: string,
    address_components[]: {
      short_name: string,
      long_name: string,
      types[]: string
    },
    geometry: {
      location: LatLng,
      location_type: GeocoderLocationType
      viewport: LatLngBounds,
      bounds: LatLngBounds
    }
   }
Google Maps JavaScript API V3 Services #3
• Geocoding

function codeAddress() {
   var address = document.getElementById("address").value;
   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);
    }
   });
 }
Google Maps JavaScript API V3 Services #4
• Reverse Geocoding
 function codeLatLng() {
   var input = document.getElementById("latlng").value;
   var latlngStr = input.split(",",2);
   var lat = parseFloat(latlngStr[0]);
   var lng = parseFloat(latlngStr[1]);
   var latlng = new google.maps.LatLng(lat, lng);
   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);
    }
   });
 }
Google Maps JavaScript API V3 Services #5
• The DirectionsRequest object literal contains the following fields:
{
    origin: LatLng | String,
    destination: LatLng | String,
    travelMode: DirectionsTravelMode,
    unitSystem: DirectionsUnitSystem,
    waypoints[]: DirectionsWaypoint,
    optimizeWaypoints: Boolean,
    provideRouteAlternatives: Boolean,
    avoidHighways: Boolean,
    avoidTolls: Boolean
    region: String
}
Google Maps JavaScript API V3 Services #6
• Street View
var fenway = new google.maps.LatLng(42.345573,-71.098326);
 var mapOptions = {
  center: fenway,
  zoom: 14,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  streetViewControl: true
 };
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
Google Maps JavaScript API V3 Map Types
• Basic Map Types
  • MapTypeId.ROADMAP
  • MapTypeId.SATELLITE
  • MapTypeId.HYBRID
  • MapTypeId.TERRAIN
Google Chart Tools
Google Chart Tools
• The Google Chart Tools enable adding live charts to any web
page.

• The advantages of the Google Chart Tools
  • A rich gallery of visualizations provided as:
     • Image charts - using a simple URL request to a Google chart server
     • Interactive charts - using a Google developed JavaScript library
  • Can read live data from a variety of data sources
  • Simple to use and free
Google Chart Tools – Image Charts #1
• Chart Gallery
  • http://code.google.com/apis/chart/docs/gallery/chart_gall.html
Google Chart Tools – Image Charts #2
• Chart Wizard
  • http://imagecharteditor.appspot.com/
Google Chart Tools – Image Charts #3
• The Google Chart API returns a chart image in response to a
URL GET or POST request.

http://chart.apis.google.com/chart?cht=<chart_type>&chd=<chart_data>&ch
s=<chart_size>&...additional_parameters...

OR

<form action='http://chart.apis.google.com/chart' method='POST'>
 <input type="hidden" name="cht" value="lc" />
 <input type="hidden" name="chtt" value="This is | my chart" />
 <input type='hidden' name='chs' value='600x200' />
 <input type="hidden" name="chxt" value="x,y" />
 <input type='hidden' name='chd' value='t:40,20,50,20,100'/>
 <input type="submit" />
</form>
Google Chart Tools – Image Charts #4
• Glossary of Chart Terms
Google Chart Tools – Image Charts #5
• Chart Play Ground
  • http://code.google.com/apis/chart/docs/chart_playground.html
Google Chart Tools – Interactive Charts #1
• The key steps for embedding a visualization in your page
   • Add a <div> to your page
  <!--Div that will hold the pie chart-->
  <div id="my_chart_div"></div>

   • Load your libraries
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
 // Load the Visualization API and the piechart package.
 google.load('visualization', '1', {'packages':['piechart']});
 // Load multiple Google packages:
 // google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']});

<script>
Google Chart Tools – Interactive Charts #2
• The key steps for embedding a visualization in your page
   • Prepare your data
     var data = new google.visualization.DataTable();
    // Declare columns and rows.
    data.addColumn('string', 'Task'); // Column 0 is type string and has label "Task".
    data.addColumn('number', 'Hours per Day'); // Column 1 is type number and has label "Hours per
Day".

    // Add data.
    data.addRows([
      ['Work', 11],
      ['Eat', 2],
      ['Commute', 2],
      ['Watch TV', 2],
      ['Sleep', 7]
      ]);

   • Create an instance of your visualization
   • Draw your visualization
Google Chart Tools – Interactive Charts #3
• The key steps for embedding a visualization in your page
   • Create an instance of your visualization

var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

   • Draw your visualization

chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
Google Chart Tools – Interactive Charts #4
• Code Example
  • http://code.google.com/apis/visualization/documentation/examples.html
Google Data Protocol
Google Data Protocol
• The Google Data Protocol provides a secure means for
external developers to write new applications that let end
users access and update the data stored by many Google
products.
• External developers can use the Google Data Protocol
directly, or they can use any of the supported programming
languages provided by the client libraries.
• The protocol currently supports two primary modes of access:
  • AtomPub
  • JSON
• http://code.google.com/apis/gdata/
Google Data Protocol – API Directory
• http://code.google.com/apis/gdata/docs/directory.html
Authentication in the Google Data Protocol
• AuthSub
• Oauth
  • http://googlecodesamples.com/oauth_playground/index.php
• ClientLogin
• Gadgets
Google Data Protocol – For Example
• Google Calendar Data API
   • Retrieving all calendars
   • https://www.google.com/calendar/feeds/default/allcalendars/full

• Picasa Web Albums Data API
  • Requesting a list of albums
  • http://picasaweb.google.com/data/feed/api/user/userID

Más contenido relacionado

La actualidad más candente

Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
drewz lin
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 
5 Reasons To Love CodeIgniter
5 Reasons To Love CodeIgniter5 Reasons To Love CodeIgniter
5 Reasons To Love CodeIgniter
nicdev
 

La actualidad más candente (20)

Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
 
MongoDB.local Dallas 2019: MongoDB Stitch Tutorial
MongoDB.local Dallas 2019: MongoDB Stitch TutorialMongoDB.local Dallas 2019: MongoDB Stitch Tutorial
MongoDB.local Dallas 2019: MongoDB Stitch Tutorial
 
A tech writer, a map, and an app
A tech writer, a map, and an appA tech writer, a map, and an app
A tech writer, a map, and an app
 
Intro firebase
Intro firebaseIntro firebase
Intro firebase
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Angular2 and TypeScript
Angular2 and TypeScriptAngular2 and TypeScript
Angular2 and TypeScript
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RS
 
SgCodeJam24 Workshop
SgCodeJam24 WorkshopSgCodeJam24 Workshop
SgCodeJam24 Workshop
 
What's New in Spring 3.1
What's New in Spring 3.1What's New in Spring 3.1
What's New in Spring 3.1
 
Azure mobile apps
Azure mobile appsAzure mobile apps
Azure mobile apps
 
State of search | drupal dinner
State of search | drupal dinnerState of search | drupal dinner
State of search | drupal dinner
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odyssey
 
Front End Development for Back End Developers - vJUG24 2017
Front End Development for Back End Developers - vJUG24 2017Front End Development for Back End Developers - vJUG24 2017
Front End Development for Back End Developers - vJUG24 2017
 
Bootiful Development with Spring Boot and React - UberConf 2018
Bootiful Development with Spring Boot and React - UberConf 2018Bootiful Development with Spring Boot and React - UberConf 2018
Bootiful Development with Spring Boot and React - UberConf 2018
 
Better Selenium Tests with Geb - Selenium Conf 2014
Better Selenium Tests with Geb - Selenium Conf 2014Better Selenium Tests with Geb - Selenium Conf 2014
Better Selenium Tests with Geb - Selenium Conf 2014
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
 
Bootiful Development with Spring Boot and React - SpringOne 2017
Bootiful Development with Spring Boot and React - SpringOne 2017Bootiful Development with Spring Boot and React - SpringOne 2017
Bootiful Development with Spring Boot and React - SpringOne 2017
 
5 Reasons To Love CodeIgniter
5 Reasons To Love CodeIgniter5 Reasons To Love CodeIgniter
5 Reasons To Love CodeIgniter
 

Destacado

Traktor 1.1.2 manual italian
Traktor 1.1.2 manual italianTraktor 1.1.2 manual italian
Traktor 1.1.2 manual italian
Virtualdeejay.net
 
кратка историја на компјутерите
кратка историја на компјутеритекратка историја на компјутерите
кратка историја на компјутерите
Georgina Dimova
 

Destacado (19)

Decreto Legislativo Capo Provvisorio Stato 16 luglio 1947, n. 708
Decreto Legislativo Capo Provvisorio Stato 16 luglio 1947, n. 708Decreto Legislativo Capo Provvisorio Stato 16 luglio 1947, n. 708
Decreto Legislativo Capo Provvisorio Stato 16 luglio 1947, n. 708
 
Class 1 course overview adlt 673 rev 2017
Class 1 course overview adlt 673 rev 2017Class 1 course overview adlt 673 rev 2017
Class 1 course overview adlt 673 rev 2017
 
AmolBhate_CV
AmolBhate_CVAmolBhate_CV
AmolBhate_CV
 
Podatoci i informacii
Podatoci i informaciiPodatoci i informacii
Podatoci i informacii
 
Estrategias para el mercado único
Estrategias para el mercado únicoEstrategias para el mercado único
Estrategias para el mercado único
 
Redes Y Medios Sociales en Banca
Redes Y Medios Sociales en BancaRedes Y Medios Sociales en Banca
Redes Y Medios Sociales en Banca
 
Meet the staff
Meet the staffMeet the staff
Meet the staff
 
Canales
CanalesCanales
Canales
 
1GEURO Europe's physical identity_FAQs
1GEURO Europe's physical identity_FAQs1GEURO Europe's physical identity_FAQs
1GEURO Europe's physical identity_FAQs
 
Traktor 1.1.2 manual italian
Traktor 1.1.2 manual italianTraktor 1.1.2 manual italian
Traktor 1.1.2 manual italian
 
Automating PhoneGap Build
Automating PhoneGap BuildAutomating PhoneGap Build
Automating PhoneGap Build
 
Lenguajes y plataformas de desarrollo
Lenguajes y plataformas de desarrolloLenguajes y plataformas de desarrollo
Lenguajes y plataformas de desarrollo
 
Rabota so kompjuter_III odd
Rabota so kompjuter_III oddRabota so kompjuter_III odd
Rabota so kompjuter_III odd
 
Cross products user manual
Cross products   user manualCross products   user manual
Cross products user manual
 
елена петковска
елена петковскаелена петковска
елена петковска
 
кратка историја на компјутерите
кратка историја на компјутеритекратка историја на компјутерите
кратка историја на компјутерите
 
Classical Art
Classical ArtClassical Art
Classical Art
 
La reina de las nieves
La reina de las nievesLa reina de las nieves
La reina de las nieves
 
UT Seminar
UT SeminarUT Seminar
UT Seminar
 

Similar a Google AJAX APIs

Advanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap IsAdvanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap Is
GoogleTecTalks
 

Similar a Google AJAX APIs (20)

Advanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap IsAdvanced Gadget And Ui Development Using Googles Ajax Ap Is
Advanced Gadget And Ui Development Using Googles Ajax Ap Is
 
Google and Beyond: Advanced Search Engine Hacking
Google and Beyond: Advanced Search Engine HackingGoogle and Beyond: Advanced Search Engine Hacking
Google and Beyond: Advanced Search Engine Hacking
 
Creating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJSCreating Modular Test-Driven SPAs with Spring and AngularJS
Creating Modular Test-Driven SPAs with Spring and AngularJS
 
Advanced Web Scraping or How To Make Internet Your Database #seoplus2018
Advanced Web Scraping or How To Make Internet Your Database #seoplus2018Advanced Web Scraping or How To Make Internet Your Database #seoplus2018
Advanced Web Scraping or How To Make Internet Your Database #seoplus2018
 
Untangling spring week5
Untangling spring week5Untangling spring week5
Untangling spring week5
 
Gat Cmigrationguide
Gat CmigrationguideGat Cmigrationguide
Gat Cmigrationguide
 
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect ModelComprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
 
Google Chronicles: Analytics And Chrome
Google Chronicles: Analytics And ChromeGoogle Chronicles: Analytics And Chrome
Google Chronicles: Analytics And Chrome
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
 
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.pptDevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
 
Going Headless with Craft CMS 3.3
Going Headless with Craft CMS 3.3Going Headless with Craft CMS 3.3
Going Headless with Craft CMS 3.3
 
Angular js
Angular jsAngular js
Angular js
 
Writing an extensible web testing framework ready for the cloud slide share
Writing an extensible web testing framework ready for the cloud   slide shareWriting an extensible web testing framework ready for the cloud   slide share
Writing an extensible web testing framework ready for the cloud slide share
 
GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to Jquery
 
The Open & Social Web - Kings of Code 2009
The Open & Social Web - Kings of Code 2009The Open & Social Web - Kings of Code 2009
The Open & Social Web - Kings of Code 2009
 
Using the Google AJAX APIs
Using the Google AJAX APIsUsing the Google AJAX APIs
Using the Google AJAX APIs
 
Extending MadCap Flare HTML5 Targets with jQuery - MadWorld 2016, Scott DeLoa...
Extending MadCap Flare HTML5 Targets with jQuery - MadWorld 2016, Scott DeLoa...Extending MadCap Flare HTML5 Targets with jQuery - MadWorld 2016, Scott DeLoa...
Extending MadCap Flare HTML5 Targets with jQuery - MadWorld 2016, Scott DeLoa...
 
Rapid Application Development with CakePHP 1.3
Rapid Application Development with CakePHP 1.3Rapid Application Development with CakePHP 1.3
Rapid Application Development with CakePHP 1.3
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks Trivia
 

Más de Yu-Wei Chuang (8)

Android N multi window
Android N multi windowAndroid N multi window
Android N multi window
 
When Web meet Native App
When Web meet Native AppWhen Web meet Native App
When Web meet Native App
 
About Mobile Web Development Thing
About Mobile Web Development ThingAbout Mobile Web Development Thing
About Mobile Web Development Thing
 
Ff os app demo
Ff os app demoFf os app demo
Ff os app demo
 
Mojito 開發 mobile web 實戰經驗談
Mojito 開發 mobile web 實戰經驗談Mojito 開發 mobile web 實戰經驗談
Mojito 開發 mobile web 實戰經驗談
 
Mojito@nodejstw
Mojito@nodejstwMojito@nodejstw
Mojito@nodejstw
 
Cocktails – Shaken, Not Stirred @osdc.tw
Cocktails – Shaken, Not Stirred @osdc.twCocktails – Shaken, Not Stirred @osdc.tw
Cocktails – Shaken, Not Stirred @osdc.tw
 
Happy facebook developer
Happy facebook developerHappy facebook developer
Happy facebook developer
 

Google AJAX APIs

  • 1. Google AJAX APIs Implement rich, dynamic web sites entirely in JavaScript and HTML. Eric 2010
  • 2. Outline • Self-Introduction • Google APIs Introduction • Google Ajax Search API • Google Maps API • Google Chart API • Google Data API
  • 6. Google APIs Introduction • 8 category APIs • Over 80 APIs we can use • http://code.google.com/
  • 7.
  • 8. Google Code Web Site • US site vs. Taiwan site
  • 9. Developer Resources • Google Code Website • http://code.google.com/ • Code Playground • http://code.google.com/apis/ajax/playground/ • Firefox & Firebug • http://moztw.org/ • Google Code Blog • http://googlecode.blogspot.com/
  • 10. Some Interesting APIs #1 • Google Account Authentication ‧ Get access into desktop or mobile applications. • Google AJAX Feed API ‧ Get access into desktop or mobile applications. • Google AJAX Language API ‧ Easily translate and detect multiple languages using JavaScript. • Android ‧ Build mobile apps for mobile devices. • Google App Engine ‧ Run your web applications on Google's infrastructure. • Google Apps ‧ Extend Google Apps, integrate or build new apps. • Blogger Data API ‧ Enable your apps to view and update Blogger content.
  • 11. Some Interesting APIs #2 • Google Calendar APIs and Tools ‧ Create and manage events, calendars • Google Chrome Extensions ‧ Modify and enhance the functionality of Google Chrome • Google Earth API ‧ Embed Google Earth into your web page. • KML ‧ Create and share content with Google Earth, Maps • Google Libraries API ‧ Load open source JavaScript libraries. • reCAPTCHA ‧ An anti-bot service. • YouTube APIs ‧ Integrate YouTube videos into your website or application.
  • 12. WHAT LANGUAGES WE USE IN THIS OFFERING • JavaScript • HTML
  • 14. Google AJAX Search API Intro • The Google AJAX Search API lets you put Google Search in your web pages with JavaScript. • Getting Start ‧ Get Google AJAX Search API Key and start coding ‧ Or Generate cut-and-paste HTML, it’s an easy way • Web Resources ‧ http://code.google.com/apis/ajaxsearch/ ‧ http://groups-beta.google.com/group/Google-AJAX-Search-API ‧ http://code.google.com/apis/ajaxsearch/samples.html
  • 15. Google AJAX Search API Wizards #1 • http://code.google.com/apis/ajaxsearch/wizards.html
  • 16. Google AJAX Search API Wizards #2 • For Example : Video Search Wizard • http://www.google.com/uds/solutions/wizards/videosearch.html • Only 4 Steps • Customize it • Tell Google about your web site • Generate code for your web page • Paste code in your web page
  • 17. "Hello World" of Google AJAX Search API #1 • Sign-up for an AJAX Search API Key
  • 18. "Hello World" of Google AJAX Search API #2 • The "Hello, World" of Google AJAX Search API • Sample Code • http://www.google.com/uds/samples/apidocs/helloworld.html • Using the Google AJAX API Loader <script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script> <script type="text/javascript"> google.load("search", "1"); </script>
  • 19. "Hello World" of Google AJAX Search API #3 • Call this function when the page has been loaded function initialize() { var searchControl = new google.search.SearchControl(); searchControl.addSearcher(new google.search.WebSearch()); searchControl.addSearcher(new google.search.NewsSearch()); searchControl.draw(document.getElementById("searchcontrol")); } • Execute Search function searchControl.execute("VW GTI"); • Use google.setOnLoadCallback to register the specified handler function google.setOnLoadCallback(initialize); • Put <div> in HTML <div id="searchcontrol">Loading</div>
  • 20. Google AJAX Search API Overview • The Search Control This provides the user interface and coordination over a number of searcher objects • Searchers It defines the interface that all searcher services must implement • GResult the search results produced by the searcher objects • Searcher Options This class configures the behavior of searcher objects
  • 21. Google AJAX Search API Overview #sample code1 // create a searcher object var sc = new google.search.SearchControl(); // add one or more searchers, specifying options as needed var options = new google.search.SearcherOptions(); options.setExpandMode(google.search.SearchControl.EXPA ND_MODE_OPEN); sc.addSearcher(new google.search.WebSearch(), options); ... // activate the search control by calling it's .draw() method sc.draw(document.getElementById("myDiv"));
  • 22. Google AJAX Search API Overview #sample code2 <!-- A collection of web search results in the search control --> <div class="gsc-results gsc-webResult"> <!-- A single web result in the search control --> <div class="gsc-result gsc-webResult"> <!-- A single web result, full structure defined below --> <div class="gs-result gs-webResult"></div> </div> ... </div> <!-- Similar pattern for local, blog, etc. --> <div class="gsc-results gsc-localResult"></div> <div class="gsc-results gsc-blogResult"></div>
  • 23. The Search Control • google.search.SearchControl • google.search.SearchForm • google.search.CustomSearchControl • GSmapSearchControl • GSvideoBar • GSnewsBar • GSvideoSearchControl • GSbookBar • GSblogBar
  • 24. google.search.SearchControl #1 • An instance of google.search.SearchControl represents a single search control on a page •是用來裝載搜尋功能的控制容器,所有搜尋功能的物件 都必須放入這個容器中才能運作。 •要建立google.search.SearchControl物件,可以使用下列 範例語法 var searchControl = new google.search.SearchControl();
  • 25. google.search.SearchControl #2 - addSearcher(searcher, opt_options) •這個函式可以將搜尋器加入搜尋控制容器中。搜尋控制 容器在最後執行搜尋動作的階段,會針對它所擁有的搜 尋器進行相對應的搜尋與顯示搜尋結果的動作 • searcher – 指定搜尋器的種類 • opt_options – 非必填引數。這個引數可以針對搜尋器進 行外觀與行為的細部設定
  • 26. google.search.SearchControl #3 - draw(element, GdrawOptions) •本函式會為每個加入搜尋控制容器的搜索器進行搜尋介 面繪製的動作。只有在所有搜索器都已加入搜索控制容 器後,才可以呼叫此函式。 • element – HTML區塊元素。我們可以將搜尋控制容器放 置到指定的HTML區塊元素之中。通常HTML區塊元素是 指HTML中的<div>元素。 • GdrawOptions – 非必填的引數。這個引數可以用來設定 搜尋結果的顯示外觀。
  • 29. google.search.SearchControl #6 - setOnKeepCallback(object, method, opt_keepLabel) •本函式可以讓我們設定緊跟在搜尋結果後面的連結,以 及按下此連結時會被呼叫的函式。當使用者點擊該連結 後,會將該筆的搜尋結果物件傳送給我們所呼叫的函式。 透過這種方式,我們就可以對搜尋結果進行更進一步的 處理。 • object – 要呼叫函式所屬的物件名稱。 • method – 要呼叫的函式名稱。 • opt_keepLabel – 功能按鈕的顯示樣式。 屬性 說明 google.search.SearchControl.KEEP_LABEL_SAVE 「保持」連結樣式 google.search.SearchControl.KEEP_LABEL_INCLUDE 「包括」連結樣式 google.search.SearchControl.KEEP_LABEL_COPY 「複製」連結樣式 google.search.SearchControl.KEEP_LABEL_BLANK 空白連結樣式 其他任意文字 顯示該文字連結
  • 32. google.search.SearchControl #9 - setSearchCompleteCallback(object, method) •我們可以透過setSearchCompleteCallback設定在搜尋動作 完成時所呼叫的函式。要注意的是,搜尋控制容器中每 一個搜尋器完成搜尋的時候就會執行一次要被呼叫的函 式。舉例來說,如果搜尋控制容器中的搜尋器有兩個, 該函式在搜尋動作完成後就會被執行兩次。 • object - 要呼叫函式所屬的物件名稱。 • method -要呼叫的函式名稱。
  • 33. google.search.SearchControl #10 - setSearchStartingCallback(object, method) •我們可以透過setSearchStartingCallback設定在搜尋動作 開始時所呼叫的函式。要注意的是,搜尋控制容器中每 一個搜尋器開始搜尋的時候就會執行一次要被呼叫的函 式。舉例來說,如果控制元件中的搜尋器有兩個,該函 式在搜尋動作開始時後就會被執行兩次。 • object - 要呼叫函式所屬的物件名稱。 • method -要呼叫的函式名稱。
  • 35. google.search.SearchForm #1 • The google.search.SearchForm object is a light weight object that is designed for exactly this use case. It provides applications with a text input element, a search button, an optional clear button, as well as all standard branding. • •要建立google.search.SearchForm物件,可以使用下列範 例語法 var searchForm = new google.search.SearchForm(enableClear, element); • enableClear – 這個引數為 ture 時,搜索輸入欄位就會包 含一個清除搜尋結果的按鈕,否則將不會有清除搜尋結 果的按鈕。 • element – HTML Element。
  • 36. google.search.SearchForm #2 - setOnSubmitCallback(object, method) • setOnSubmitCallback可以讓我們設定點選搜尋按鈕後所 呼叫的物件與函式,此外搜尋輸入欄位的值也會被傳遞 到要被呼叫的函式中。 • object - 要呼叫函式所屬的物件名稱。 • method -要呼叫的函式名稱。
  • 37. google.search.SearchForm #3 - setOnClearCallback(object, method) •本函式將會設定按下搜索輸入欄位的「清除」按鈕時被 呼叫的物件與函式。如果在建立google.search.SearchForm 物件時,沒有建立清除搜尋結果的按鈕,則呼叫此函式 時會發生錯誤。此外,搜尋輸入欄位的值也會被傳遞到 要被呼叫的函式中。 • object - 要呼叫函式所屬的物件名稱。 • method -要呼叫的函式名稱。
  • 40. Searchers #2 • google.search.WebSearch var searcher = new google.search.WebSearch(); • google.search.LocalSearch var searcher = new google.search.LocalSearch(); • google.search.VideoSearch var searcher = new google.search.VideoSearch(); • google.search.BlogSearch var searcher = new google.search.BlogSearch();
  • 41. Searchers #3 • google.search.NewsSearch var searcher = new google.search.NewsSearch(); • google.search.ImageSearch var searcher = new google.search.ImageSearch(); • google.search.BookSearch var searcher = new google.search.BookSearch(); • google.search.PatentSearch var searcher = new google.search.PatentSearch();
  • 42. GResult #1 • Result objects are produced using a JSON encoding of server search requests. • 當我們透過搜尋器進行搜尋動作後,除了會在指定的網 頁元素位置上顯示搜尋結果外,也會根據搜尋器的種類 回傳不同的搜尋結果物件。瞭解搜尋結果物件的屬性, 可以讓我們對搜尋結果物件進行更進一步的處理
  • 43. GResult #2 • Result objects are produced using a JSON encoding of server search requests. • 當我們透過搜尋器進行搜尋動作後,除了會在指定的網 頁元素位置上顯示搜尋結果外,也會根據搜尋器的種類 回傳不同的搜尋結果物件。瞭解搜尋結果物件的屬性, 可以讓我們對搜尋結果物件進行更進一步的處理
  • 44. Searcher Options • When adding a searcher to the search control, the GsearcherOptionsgoogle.search.SearcherOptions object may be specified. // create a searcher options object // set up for open expansion mode // load a searcher with these options var options = new google.search.SearcherOptions(); options.setExpandMode(google.search.SearchControl.EXPAND_MOD E_OPEN); searchControl.addSearcher(new google.search.WebSearch(), options);
  • 45. DrawOptions Options • When asking a search control to draw, you must specify a container for the control to draw within. • In addition to this required parameter, the search control's .draw() method also accepts an optional google.search.DrawOptions object. // create a drawOptions object var drawOptions = new google.search.DrawOptions(); drawOptions.setDrawMode(google.search.SearchControl.DRAW_MO DE_TABBED); searchControl.draw(element, drawOptions);
  • 47. Google Maps API Family • Google Maps has a wide array of APIs that let you embed the robust functionality and everyday usefulness of Google Maps into your own website and applications
  • 48. Google Maps JavaScript API V3 • V3: The Solution for Maps Applications for both the Desktop and Mobile Devices • The version 3 of the Google Maps API will look similar to the existing version 2 of the Google Maps API. • Who uses Maps API: • Yelp: http://www.youtube.com/watch?v=jWmLCpE_nwg • 地圖日記 • Web Resources • http://groups.google.com/group/google-maps-js-api-v3 • http://code.google.com/apis/maps/documentation/javascript/
  • 49. "Hello World" of Google Maps V3 #1 • Sample Code URL • http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html • Declaring Your Application as HTML5 <!DOCTYPE html> • 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>
  • 50. "Hello World" of Google Maps V3 #2 • Map DOM Elements <div id="map_canvas" style="width: 100%; height: 100%"></div> • Map Options var myLatlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; • Create instance var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  • 51. Geolocation • Geolocation refers to the identification of the geographic location of a user or computing device via a variety of data collecton mechanisms. • Newer browsers are starting to support the W3C Geolocation standard. // Try W3C Geolocation method (Preferred) if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); …… });}
  • 52. Developing for Mobile Devices • You can detect iPhone and Android devices by inspecting the navigator.userAgent function detectBrowser() { var useragent = navigator.userAgent; var mapdiv = document.getElementById("map_canvas"); if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) { mapdiv.style.width = '100%'; mapdiv.style.height = '100%'; } else { mapdiv.style.width = '600px'; mapdiv.style.height = '800px'; } }
  • 53. Localization in the V3 Maps API • Language Localization <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=ja"> • Region Localization <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&region=GB">
  • 54. Base objects - LatLng • LatLng is a point in geographical coordinates, latitude and longitude. var latlng = new google.maps.LatLng(60, 105); Methods Return Value Description equals(other:LatLng) boolean Comparison function. Returns the latitude in lat() number degrees. Returns the longitude in lng() number degrees. Converts to string toString() string representation. Returns a string of the form toUrlValue() string "lat,lng" for this LatLng.
  • 55. Base objects – LatLngBounds#1 • A LatLngBounds instance represents a rectangle in geographical coordinates. var c = new google.maps.LatLngBounds(latlngA, latlngB); Methods Return Value Description Returns true if the given lat/lng is in contains(latLng:LatLng) boolean this bounds. Returns true if this bounds equals(other:LatLngBounds) boolean approximately equals the given bounds. Extends this bounds to contain the extend(point:LatLng) LatLngBounds given point. Computes the center of this getCenter() LatLng LatLngBounds Returns the north-east corner of this getNorthEast() LatLng bounds. Returns the south-west corner of this getSouthWest() LatLng bounds. Returns true if this bounds shares any intersects(other:LatLngBounds) boolean points with this bounds. isEmpty() boolean Returns if the bounds are empty.
  • 56. Base objects – LatLngBounds#2 Converts the given map bounds to a toSpan() LatLng lat/lng span. toString() string Converts to string. Returns a string of the form "lat_lo,lng_lo,lat_hi,lng_hi" for this bounds, where "lo" corresponds to the toUrlValue(precision?:number) string southwest corner of the bounding box, while "hi" corresponds to the northeast corner of that box. Extends this bounds to contain the union(other:LatLngBounds) LatLngBounds union of this and the given bounds.
  • 57. google.maps.Map • Language Localization varmap = new google.maps.Map(document.getElementById("map_canvas"), myOptions); • Some Functions setCenter(latlng:LatLng) setMapTypeId(mapTypeId:MapTypeId) setOptions(options:MapOptions) setZoom(zoom:number) getMapTypeId() getZoom()
  • 58. Google Maps Javascript API V3 Controls • Navigation control • Scale control • MapType control • You don't access or modify controls directly. Instead, you modify the map's MapOptions fields which affect the visibility and presentation of controls. You can adjust control presentation upon instantiating your map (with appropriate MapOptions) or modify a map dynamically by calling setOptions() to change the map's options.
  • 59. The Default Control Set Control Large Screens Small Screens iPhone Android Large Small Mini- Pan/Zoom for Zoom for sizes "Android" Navigation sizes larger Not present smaller than control than 400x350px 400x350px Horizontal Bar Dropdown for Same as Same as for screens screens smaller MapType Large/Small Large/Small larger than than 320px Screens Screens 320px wide wide Scale Not present Not present Not present Not present
  • 60. Disabling the Default UI 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); }
  • 61. Adding Controls to the Map { navigationControl: boolean, mapTypeControl: boolean, scaleControl: boolean } function initialize() { var myOptions = { zoom: 4, center: new google.maps.LatLng(-33, 151), navigationControl: true, mapTypeControl : true, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }
  • 62. Control Options • Navigation control • google.maps.NavigationControlStyle.SMALL • google.maps.NavigationControlStyle.ZOOM_PAN • google.maps.NavigationControlStyle.ANDROID • google.maps.NavigationControlStyle.DEFAULT • MapType control • google.maps.MapTypeControlStyle.HORIZONTAL_BAR • google.maps.MapTypeControlStyle.DROPDOWN_MENU • google.maps.MapTypeControlStyle.DEFAULT
  • 63. Control Positioning function initialize() { var myOptions = { zoom: 12, center: new google.maps.LatLng(-28.643387, 153.612224), mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, position: google.maps.ControlPosition.BOTTOM }, navigationControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.ZOOM_PAN, position: google.maps.ControlPosition.TOP_RIGHT }, scaleControl: true, scaleControlOptions: { position: google.maps.ControlPosition.TOP_LEFT } } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }
  • 64. Google Maps Javascript API V3 Events #1 • UI Events • Other Events • click • drag • dblclick • dragend • mouseup • dragstart • mousedown • maptypeid_changed • mouseover • rightclick • mouseout • Map Events • zoom_changed • center_changed • bounds_changed • mousedown • mouseover • mouseout
  • 65. Google Maps Javascript API V3 Events #2 var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Hello World!" }); google.maps.event.addListener(marker, 'click', function() { map.setZoom(8); });
  • 66. Google Maps Javascript API V3 Events #3 • Accessing Arguments in UI Events • MouseEvent google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); }); Properties Type Description The latitude/longitude that was below the latLng LatLng cursor when the event occurred.
  • 67. Google Maps JavaScript API V3 Overlays #1 • Overlays are objects on the map that are tied to latitude/longitude coordinates, so they move when you drag or zoom the map. Overlays reflect objects that you "add" to the map to designate points, lines, areas, or collections of objects. • several types of overlays: • markers • polylines • overlay map types • info window • custom overlays
  • 68. Google Maps JavaScript API V3 Overlays #2 • Adding Overlays 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, title:"Hello World!" }); // To add the marker to the map, call setMap(); marker.setMap(map);
  • 69. Google Maps JavaScript API V3 Overlays #3 • Removing Overlays • http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html // Removes the overlays from the map, but keeps them in the array function clearOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } }} // Shows any overlays currently in the array function showOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(map); } }} // Deletes all markers in the array by removing references to them function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } markersArray.length = 0; }}
  • 70. Google Maps JavaScript API V3 Overlays #4 • Markers 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!" });
  • 71. Google Maps JavaScript API V3 Overlays #5 • Simple Icons 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 var marker = new google.maps.Marker({ position: myLatLng, map: map, shadow: shadow, icon: image, shape: shape, title: beach[0], zIndex: beach[3] });
  • 72. Google Maps JavaScript API V3 Overlays #6 • Polylines • A polyline supports the following stroke styles: • strokeColor • strokeOpacity • strokeWeight 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);
  • 73. Google Maps JavaScript API V3 Overlays #7 • Polygons • A polygons supports the ploylines stroke styles and fill styles: • fillColor • fillOpacity 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);
  • 74. Google Maps JavaScript API V3 Overlays #8 • Ground var oldmap = new google.maps.GroundOverlay( "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", imageBounds); oldmap.setMap(map);
  • 75. Google Maps JavaScript API V3 Overlays #9 • InfoWindows • Methods Methods Return Value Description close() None Closes this InfoWindow getContent() string|Node getPosition() LatLng getZIndex() number open(map:Map|StreetViewPanora None ma, anchor?:MVCObject) setContent(content:string|Node) None • InfoWindow options • content • pixelOffset • position • maxWidth
  • 76. Google Maps JavaScript API V3 Overlays #10 • KML and GeoRSS Layers • The Google Maps API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file.
  • 77. Google Maps JavaScript API V3 Overlays #11 • The Traffic Layer • The Bicycling Layer • http://gmaps-samples.googlecode.com/svn/trunk/mapcoverage_filtered.html
  • 78. Google Maps JavaScript API V3 Services #1 • 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. • 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.
  • 79. Google Maps JavaScript API V3 Services #2 • The GeocodeRequest object literal contains the following fields: • address: string (*) • latLng: LatLng (*) • bounds: LatLngBound • region: string • Geocoding Results results[]: { types[]: string, formatted_address: string, address_components[]: { short_name: string, long_name: string, types[]: string }, geometry: { location: LatLng, location_type: GeocoderLocationType viewport: LatLngBounds, bounds: LatLngBounds } }
  • 80. Google Maps JavaScript API V3 Services #3 • Geocoding function codeAddress() { var address = document.getElementById("address").value; 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); } }); }
  • 81. Google Maps JavaScript API V3 Services #4 • Reverse Geocoding function codeLatLng() { var input = document.getElementById("latlng").value; var latlngStr = input.split(",",2); var lat = parseFloat(latlngStr[0]); var lng = parseFloat(latlngStr[1]); var latlng = new google.maps.LatLng(lat, lng); 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); } }); }
  • 82. Google Maps JavaScript API V3 Services #5 • The DirectionsRequest object literal contains the following fields: { origin: LatLng | String, destination: LatLng | String, travelMode: DirectionsTravelMode, unitSystem: DirectionsUnitSystem, waypoints[]: DirectionsWaypoint, optimizeWaypoints: Boolean, provideRouteAlternatives: Boolean, avoidHighways: Boolean, avoidTolls: Boolean region: String }
  • 83. Google Maps JavaScript API V3 Services #6 • Street View var fenway = new google.maps.LatLng(42.345573,-71.098326); var mapOptions = { center: fenway, zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP, streetViewControl: true }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  • 84. Google Maps JavaScript API V3 Map Types • Basic Map Types • MapTypeId.ROADMAP • MapTypeId.SATELLITE • MapTypeId.HYBRID • MapTypeId.TERRAIN
  • 86. Google Chart Tools • The Google Chart Tools enable adding live charts to any web page. • The advantages of the Google Chart Tools • A rich gallery of visualizations provided as: • Image charts - using a simple URL request to a Google chart server • Interactive charts - using a Google developed JavaScript library • Can read live data from a variety of data sources • Simple to use and free
  • 87. Google Chart Tools – Image Charts #1 • Chart Gallery • http://code.google.com/apis/chart/docs/gallery/chart_gall.html
  • 88. Google Chart Tools – Image Charts #2 • Chart Wizard • http://imagecharteditor.appspot.com/
  • 89. Google Chart Tools – Image Charts #3 • The Google Chart API returns a chart image in response to a URL GET or POST request. http://chart.apis.google.com/chart?cht=<chart_type>&chd=<chart_data>&ch s=<chart_size>&...additional_parameters... OR <form action='http://chart.apis.google.com/chart' method='POST'> <input type="hidden" name="cht" value="lc" /> <input type="hidden" name="chtt" value="This is | my chart" /> <input type='hidden' name='chs' value='600x200' /> <input type="hidden" name="chxt" value="x,y" /> <input type='hidden' name='chd' value='t:40,20,50,20,100'/> <input type="submit" /> </form>
  • 90. Google Chart Tools – Image Charts #4 • Glossary of Chart Terms
  • 91. Google Chart Tools – Image Charts #5 • Chart Play Ground • http://code.google.com/apis/chart/docs/chart_playground.html
  • 92. Google Chart Tools – Interactive Charts #1 • The key steps for embedding a visualization in your page • Add a <div> to your page <!--Div that will hold the pie chart--> <div id="my_chart_div"></div> • Load your libraries <!--Load the AJAX API--> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['piechart']}); // Load multiple Google packages: // google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']}); <script>
  • 93. Google Chart Tools – Interactive Charts #2 • The key steps for embedding a visualization in your page • Prepare your data var data = new google.visualization.DataTable(); // Declare columns and rows. data.addColumn('string', 'Task'); // Column 0 is type string and has label "Task". data.addColumn('number', 'Hours per Day'); // Column 1 is type number and has label "Hours per Day". // Add data. data.addRows([ ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); • Create an instance of your visualization • Draw your visualization
  • 94. Google Chart Tools – Interactive Charts #3 • The key steps for embedding a visualization in your page • Create an instance of your visualization var chart = new google.visualization.PieChart(document.getElementById('chart_div')); • Draw your visualization chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
  • 95. Google Chart Tools – Interactive Charts #4 • Code Example • http://code.google.com/apis/visualization/documentation/examples.html
  • 97. Google Data Protocol • The Google Data Protocol provides a secure means for external developers to write new applications that let end users access and update the data stored by many Google products. • External developers can use the Google Data Protocol directly, or they can use any of the supported programming languages provided by the client libraries. • The protocol currently supports two primary modes of access: • AtomPub • JSON • http://code.google.com/apis/gdata/
  • 98. Google Data Protocol – API Directory • http://code.google.com/apis/gdata/docs/directory.html
  • 99. Authentication in the Google Data Protocol • AuthSub • Oauth • http://googlecodesamples.com/oauth_playground/index.php • ClientLogin • Gadgets
  • 100. Google Data Protocol – For Example • Google Calendar Data API • Retrieving all calendars • https://www.google.com/calendar/feeds/default/allcalendars/full • Picasa Web Albums Data API • Requesting a list of albums • http://picasaweb.google.com/data/feed/api/user/userID