Google Earth API開發者指南(初級)

Google Earth API開發者指南(初級)

Google Earth API開發者指南(序)http://bbs.godeyes.cn/Announce/Announce.asp?BoardID=100&ID=335615



第一個小程序——“Hello World”

記得在學校上編程課時,無論是Basic還是C,課本第一個示例都是“Hello World”。今天,我們開始學習Google Earth API,仍然以這個最簡單的小示例開始。下列JavaScript源代碼教您如何創建一個包含Google Earth的網頁。

<html>
  <head>
    <title>Hello Google Earth!</title>
    <!-- *** Replace the key below below with your own API key, available at http://code.google.com/apis/maps/signup.html *** -->
    <script src="http://www.google.com/jsapi?key=ABCDEF";></script>
    <script>

google.load("earth", "1");



var ge = null;



function init() {
  google.earth.createInstance("map3d", initCallback, failureCallback);

}



function initCallback(object) {
  ge = object;
  ge.getWindow().setVisibility(true);

}



function failureCallback(object) {

}


    </script>
  </head>
  <body οnlοad='init()';


      <div>
        Hello, Earth!
      </div>


      <div id='map3d_container'
           style='border: 1px solid silver; height: 600px; width: 800px;'>
        <div id='map3d' style='height: 100%;'></div>
      </div>
  </body>

</html>

您可以直接把這段代碼複製下來,把裏面的“Key”換成您自己申請的Key值(詳見序)。如果您不方便申請Key,又想看看這段源代碼的運行效果,那麼也沒關係,您可以點擊查看這個鏈接(http://www.google.com/earth/plugin/examples/helloearth/)——前提是您必須已安裝了Google Earth插件。

上面這段代碼中,您需要注意四個方面(上述代碼中已用綠色粗體字顯示):

?      Google Earth API腳本語句必須包含script標籤,即“<script>”。

?      用div標籤把Google Earth窗口框起來。

?      用JavaScript函數來創建Google Earth對象。

?      在body標籤的onLoad事件來初始化Google Earth對象。



下面就對上述要點做一簡單說明:



加載Google Earth API

<script src="http://www.google.com/jsapi?key=ABCDEF";></script>

想必大家都已經知道,在編寫Google Earth網頁時,必須先申請key。http://www.google.com/jsapi?key=ABCDEF是一個鏈接,鏈接那一頭包含了您要使用Google Earth API所需要的所有Javascript元件、標籤和定義文件。此例中key值爲假設值“ABCDEF”。



DOM

<div id='map3d_container'
    style='border: 1px solid silver; height: 600px; width: 800px;'>
    <div id='map3d' style='height: 100%;'></div>

</div>

由於要在網頁上顯示Google Earth窗口,所以必須給它留些位置。這人“位置”就是用已命名的div標籤來創建,並以此來獲取瀏覽器文檔對象模型的參考。在這個示例中,div標籤被命名爲“map_3d_container”,其長寬均由相應屬性設定。



加載Google Earth

<body οnlοad='init()' id='body'>

當HTML頁面編譯時,文檔對象模型(DOM)以及所有外部圖像、腳本均被融合到文檔(document)對象中。爲了確保頁面完全加載後地圖能顯示在指定位置,我們可以單步調試,當<body>標籤內的onLoad事件被觸發時,僅執行ge對象的函數,仔細觀察運行效果。這樣做是爲了避免不確定因素或人爲失誤,使我們對地圖的繪製與顯示得以掌控。





創建地標

地標是Google Earth裏最常用的功能之一,它用一顆小圖釘來表示地標製作/發佈者的指定方位。您可以對地標進行編輯——修改名稱或圖標,也可以加入其他地理屬性一。下列代碼創建了一個地標,該地標位於Google位於美國硅谷總部的園區。

var placemark = ge.createPlacemark('');

placemark.setName("You are at Google");

ge.getFeatures().appendChild(placemark);



// Create style map for placemark

var normal = ge.createIcon('');

normal.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');

var iconNormal = ge.createStyle('');

iconNormal.getIconStyle().setIcon(normal);

var highlight = ge.createIcon('');

highlight.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');

var iconHighlight = ge.createStyle('');

iconHighlight.getIconStyle().setIcon(highlight);

var styleMap = ge.createStyleMap('');

styleMap.setNormalStyle(iconNormal);

styleMap.setHighlightStyle(iconHighlight);

placemark.setStyleSelector(styleMap);
 

// Create point

var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);

var point = ge.createPoint('');

point.setLatitude(la.getLatitude());

point.setLongitude(la.getLongitude());

placemark.setGeometry(point);

地標效果如下圖所示

850)this.width=850;" style="CURSOR: hand" οnclick=javascript:window.open(this.src); src="http://bbs.godeyes.cn/upload/2008/07/03/165253.jpg" οnlοad="javascript:if(this.width>850)this.width=850;" align=absMiddle border=0>



創建地標過程中,您必須指定兩項內容:

?      地標名稱。上例中,地標名稱爲“You are at Google”。

?      地標位置。即明確的經緯度和任意海撥。上例中,經緯度由“LookAt”指定(“LookAt”用來定義視角,即瀏覽地標的方向、角度、高度)。





創建氣泡提示

創建地標之後,您可以添加一個“氣泡提示”,對地標加以說明。“氣泡提示”完全支持HTML格式,也就是說,說明內容可以包含文本、圖片、表格、超鏈接等。目前“氣泡”有三種類型:

?      特徵氣泡

?      文字氣泡

?      DIV氣泡

下列代碼將創建一個特徵氣泡:

var b = ge.createFeatureBalloon('');

b.setFeature(marker);

b.setMaxWidth(800);

ge.setBalloon(b);



下列代碼將創建一個文字氣泡,文字顯示爲珠穆朗瑪峯,字體設爲粗體大號:

var b = ge.createHtmlStringBalloon('');

b.setMaxWidth(300);

b.setFeature(feature);

b.setContentString (

'<b.setContentString (

'<img src="http://www.google.com/intl/en_ALL/images/logo.gif";>' +

'<font size=20>Mount Everest</font><br><font size=-2>on top of the world ' + 'window</font>');

ge.setBalloon(b);

效果如下圖所示:

850)this.width=850;" style="CURSOR: hand" οnclick=javascript:window.open(this.src); src="http://bbs.godeyes.cn/upload/2008/07/03/165414.jpg" width=850 οnlοad="javascript:if(this.width>850)this.width=850;" align=absMiddle border=0>



下列代碼將創建DIV 氣泡:

var b = ge.createHtmlDivBalloon('');

b.setMaxWidth(800);

b.setFeature(feature);

var div = document.createElement('DIV');

div.innerHTML =
        '<img src="http://www.google.com/googlegulp/images/logo.gif";><br>'
        + '<a href="http://www.google.com/googlegulp/";>Google Gulp</a>';

b.setContentDiv(div);

ge.setBalloon(b);



您可以通過改變字體、文字顏色、圖片以及排版格式來進行自定義。如果要關閉說明框,可以用下面這條Javascript語句:ge.setBalloon(null);





如何控制遊覽視角

您可以用LookAt對象來指定Google Earth察看點、察看距離及角度。下例代碼把察看位置向北移動7度(經度),向東移動7度(緯度)。

var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);

lookAt.setLatitude(lookAt.getLatitude() + 7.0);

lookAt.setLongitude(lookAt.getLongitude() + 7.0);

ge.getView().setAbstractView(lookAt);





創建路徑

在Google Earth內可創建多種類型的路徑,並且可根據您的數據進行定製。路徑由“lineString”對象創建,可以通過定義一串連續的線段來創建彎折路徑。當使用lineString對象時,您必須指定lineString是否與地面相連。Tessellate屬性可以將直線分割成若干線段。

var lineString;

lineString = ge.createLineString('');

var lineStringPlacemark = ge.createPlacemark('');

lineStringPlacemark.setGeometry(lineString);

lineString.setTessellate(true);

ge.getDocument().getFeatures().appendChild(lineStringPlacemark);



addToLineString(lineString,  0,   0, 0);

addToLineString(lineString, .1, .05, 0);

addToLineString(lineString,  0, .10, 0);

addToLineString(lineString, .1, .15, 0);

addToLineString(lineString,  0, .20, 0);

addToLineString(lineString, .1, .25, 0);

下圖即爲Google Earth中創建的路徑:

850)this.width=850;" style="CURSOR: hand" οnclick=javascript:window.open(this.src); src="http://bbs.godeyes.cn/upload/2008/07/03/165502.jpg" οnlοad="javascript:if(this.width>850)this.width=850;" align=absMiddle border=0>



改變路徑樣式

可以通過指定顏色和寬度來確定路徑樣式。下列JavaScript代碼針對上述路徑,增加了線條寬度,並把顏色改爲藍色。樣式更改後效果如下圖所示。

var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();

lineStyle.setWidth(lineStyle.getWidth() + 2);

lineStyle.getColor().set('66ff0000');

850)this.width=850;" style="CURSOR: hand" οnclick=javascript:window.open(this.src); src="http://bbs.godeyes.cn/upload/2008/07/03/165552.jpg" οnlοad="javascript:if(this.width>850)this.width=850;" align=absMiddle border=0>
 



創建多邊形

您可以通過多邊形功能來創建房屋或其他形狀。下列代碼,創建了一個矩形,其內外邊框均設爲白色。

var polygonPlacemark = ge.createPlacemark('');

polygonPlacemark.setGeometry(ge.createPolygon(''));

var outer = ge.createLinearRing('');

polygonPlacemark.getGeometry().setOuterBoundary(outer);

ge.getDocument().getFeatures().appendChild(polygonPlacemark);



// Square outer boundary

var center = ge.createLookAt('');

center = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);

var coords = outer.getCoordinates();

var lat = center.getLatitude();

var lon = center.getLongitude();

coords.pushLatLngAlt(lat - .05, lon - .05, 0);

coords.pushLatLngAlt(lat - .05, lon + .05, 0);

coords.pushLatLngAlt(lat + .05, lon + .05, 0);

coords.pushLatLngAlt(lat + .05, lon - .05, 0);



// Create a square inner boundary

polygonPlacemark.getGeometry().getInnerBoundaries().
  appendChild(ge.createLinearRing(''));

coords = polygonPlacemark.getGeometry().getInnerBoundaries().getFirstChild().
  getCoordinates();

coords.pushLatLngAlt(lat - .02, lon - .02, 0);

coords.pushLatLngAlt(lat - .02, lon + .02, 0);

coords.pushLatLngAlt(lat + .02, lon + .02, 0);

coords.pushLatLngAlt(lat + .02, lon - .02, 0);



效果如下圖所示

850)this.width=850;" style="CURSOR: hand" οnclick=javascript:window.open(this.src); src="http://bbs.godeyes.cn/upload/2008/07/03/165621.jpg" οnlοad="javascript:if(this.width>850)this.width=850;" align=absMiddle border=0>



更改多邊形樣式

跟路徑一樣,您可以通過改變顏色和邊框寬度,自己設定多邊形樣式。見下例,把矩形邊設爲紅色,邊框爲藍色。

var lineStyle = polygonPlacemark.getStyleSelector().getLineStyle();

lineStyle.setWidth(lineStyle.getWidth() + 2);

lineStyle.getColor().set('66ff0000');

polygonPlacemark.getStyleSelector().getPolyStyle().getColor().set('660000ff');

850)this.width=850;" style="CURSOR: hand" οnclick=javascript:window.open(this.src); src="http://bbs.godeyes.cn/upload/2008/07/03/165645.jpg" οnlοad="javascript:if(this.width>850)this.width=850;" align=absMiddle border=0>
 



使用在線地標

在線地標,顧名思義,必然有一項屬性超鏈接,該鏈接指向存放在網絡上的地標文件,包含以下三類:

?      圖標文件、地面疊加圖、屏幕疊加圖。

?      模型(SketchUp文件尤佳)。

?      KML或KMZ文件。

鏈接文件可以存放在本地,也可存放在遠程服務器上。在線地標的最大優勢就是可以方便有效地管理、使用大容量或更新頻繁的文件。如果在本地打開大容量地標文件,那對機器硬件將是一大考驗。

下列代碼將創建一款在線地標: s

var networkLink = ge.createNetworkLink("");

networkLink.setDescription("NetworkLink open to fetched content");

networkLink.setName("Open NetworkLink");

networkLink.setFlyToView(true);  

var link = ge.createLink("");

link.setHref("http://kml-samples.googlecode.com"; +
             "/svn/trunk/kml/NetworkLink/placemark.kml");

networkLink.setLink(link);

ge.getFeatures().appendChild(networkLink);



管理事件

JavaScript語言是基於事件驅動的,也就是說,事件的產生將激發JavaScript作出反應,程序把結果反饋給用戶。例如,在瀏覽器內,用戶的鍵盤、鼠標動作將觸發文檔對象模型(DOM)內的事件。事件內的代碼會先將其監聽模塊註冊,當事件激活/產生時,便立即執行相關反饋代碼。



Google Earth API的事件由GEvent命名空間裏的函數來控制的。每一個Google Earth API對象都對應若干事件。例如,“KmlPlacemark”對象有“Click”(單擊),“dblclick”(雙擊),“move”(移動)等事件。每種事件都只適應特定操作,比如,用戶在Google Earth裏移動鼠標就會觸發“mousemove”事件。在下列代碼中,您將看到事件是如何被管理的:

function myEventListener(kmlEvent) {
  var targetType = kmlEvent.getTarget().getType();
  var currentTargetType = kmlEvent.getCurrentTarget().getType();
  var button = kmlEvent.getButton());
  var clientX = kmlEvent.getClientX();
  var clientY = kmlEvent.getClientY();
  var screenX = kmlEvent.getScreenX();
  var screenY = kmlEvent.getScreenY();
  var latitude = kmlEvent.getLatitude();
  var longitude = kmlEvent.getLongitude();
  var altitude = kmlEvent.getAltitude();
  var didHitGlobe = kmlEvent.getDidHitGlobe();
  var altKey = kmlEvent.getAltKey();
  var ctrlKey = kmlEvent.getCtrlKey();
  var shiftKey = kmlEvent.getShiftKey();
  var timeStamp = kmlEvent.getTimeStamp();

}



// This will trigger myEventListener() when user clicks on 'placemark',

// and will pass in a KmlEvent object.

google.earth.addEventListener(placemark, "mousedown", myEventListener);



// This will trigger myEventListener() when user clicks on the globe,

// and will pass in a KmlEvent object.

google.earth.addEventListener(ge.getGlobe(), "mousedown", myEventListener);



// This will trigger myEventListener() when user clicks anywhere in the window,

// and will pass in a KmlEvent object.

google.earth.addEventListener(ge.getWindow(), "mousedown", myEventListener);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章