本文中將使用工具輕松構(gòu)建終極的Hello World mashup:Google地圖mashup……
查看下面的 HTML 片斷來了解這一結(jié)構(gòu):
<table> <tr> <td valign="top"> <div id="google_map_div" style="width: 500px; height: 300px"> </div> </td> <td valign="top"> <p id="getLocations_div" align="center"> <> <form id="getLocationsForm"> <input value="Get the Locations" type="submit" onclick="javascript:getLocationsAndMap();return false" /> </form> </p> <p> <div id="locations_div"> <> </div> </p> </td> </tr> </table> |
請注意,當(dāng)用戶按下按鈕時,將觸發(fā)一個onclick 事件。該事件連接到了前述getLocationsAndMap() 函數(shù),該函數(shù)將調(diào)用針對REST 服務(wù)的XMLHttpRequest。您已經(jīng)看到,getLocationsAndMapCallback() 函數(shù)之后會將服務(wù)響應(yīng)從JSON 文本轉(zhuǎn)換為注入到DOM 的HTML。
現(xiàn)在,您需要將地址組合到Google 地圖中。首先,getLocationsAndMapCallback() 中的JavaScript 代碼會編寫HTML ,因此每個地址都會有一個調(diào)用JavaScript 函數(shù)的錨定標(biāo)記。函數(shù)showAddress()和代碼會傳遞所點擊的位置地址。以上代碼中g(shù)etLocationsAndMapCallback()函數(shù)的 TODO注釋替換為這行代碼:
var anchor = ‘<a href="irrelevant" onclick="javascript:showAddress(\‘‘+ response.locations.location[i].address+‘\‘);‘+ ‘ return false">‘; |
這會為每個地址創(chuàng)建一個錨定標(biāo)記,單擊地址時就會觸發(fā)showAddress() 函數(shù)。
下一步,showAddress() 函數(shù)會連接到Google 地圖 API,由它真正在地圖中顯示傳遞過來的地址。這是通過Google 提供的樣板代碼來完成的。請注意以下代碼中的GMap2 和 geocoder 對象,它們都是作為Google地圖API的一部分提供的。該代碼將檢索地圖,然后更新HTML 文檔的google_map_div div 標(biāo)記。
function showAddress(address) { var map = new GMap2( document.getElementById("google_map_div")); var geocoder = new GClientGeocoder(); geocoder.getLatLng(address, function(point) { if (!point) { alert(address + " not found"); } else { map.setCenter(point, 13); var marker = new GMarker(point); map.addOverlay(marker); marker.openInfoWindowHtml(address); } } ); } |
無論您相信與否,這樣就完成了Ajax支持的Google 地圖 mashup!在本教程中我還沒有展示完整的文件,我展示的是重要部分。查看下載一節(jié),獲取完整代碼。