2008年12月23日 星期二

Google Search api 心得

google search api 提供了很多種搜尋 如
localSearch,WebSearch,BlogSearch,imgeSearch,NewsSearch,BookSearch and
PatentSearch 等

這裡我就以一個範例大致介紹一下imgeSearch 的部分;

這個範例的內涵是輸入一個字串,如taipei,找出google imgeSearch 的資料,並將圖片貼在網頁上(在右側顯示前四張圖片)

由於他網站google search api 上的說明還蠻淺顯易懂的有興趣的可以看http://code.google.com/intl/
zh-TW/apis/ajaxsearch/documentation/

結果如下



-------------------------------------------------
以下示範例code


1. head 部分

引用google api ,用google account可以申請
如下
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAy-Ulx72brHCd0DtCPGmBFRRbZEp8C4_MgJNX2IGnI57Zyu60bBSf-cAEuJBLHkAS5ENN-3MHGHIGtQ"></script>


2. CSS 部分

<style type="text/css">


#searchcontrol { width : 50% }
#photo{
top: 0%;
position: absolute;
left: 50%;
}

</style>


3. javascript 部分

// 引用google search api
google.load('search', '1.0');

function Init() {
// Create a search control
var searchControl = new google.search.SearchControl();

// add searcher imgeSearch, also have many other search like
// localSearch,WebSearch,BlogSearch,NewsSearch,BookSearch and PatentSearch
// see more to http://code.google.com/intl/zh-TW/apis/ajaxsearch/documentation/#The_Hello_World_of_Google_Search

searchControl.addSearcher(new google.search.ImageSearch());

// tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));

// execute an inital search
searchControl.execute("taipei");

// establish a Search Complete Callback
searchControl.setSearchCompleteCallback(this, this.MyKeepHandler);
}



function MyKeepHandler(sc, searcher) {

// record the search result
if (searcher.results && searcher.results.length > 0) {
idx = 0;
url = [];
for (var i=0; i<searcher.results.length; i++) {
// unescapedUrl is the pic url
// see more http://code.google.com/intl/zh-TW/apis/ajaxsearch/documentation/reference.html#_class_GimageResult
url[i] = searcher.results[i].unescapedUrl;
} //end of for
}//end of if

// set the pic to the html frame
picture1=document.getElementById("pic1")
picture1.src=url[0];

picture2=document.getElementById("pic2")
picture2.src=url[1];

picture3=document.getElementById("pic3")
picture3.src=url[2];

picture4=document.getElementById("pic4")
picture4.src=url[3];
}


4. body部分

<body onload="Init()">
<div id="searchcontrol">Loading</div>
<div id="saved_results"></div>
<div id="photo" >
<img id='pic1' src='' width=300px height=200px>
<img id='pic2' src='' width=300px height=200px>
<img id='pic3' src='' width=300px height=200px>
<img id='pic4' src='' width=300px height=200px>
</div>
</body>

沒有留言: