GoogleMap在js中的應用

<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> 
<script type="text/javascript"> 
  function initialize() { 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 
    var myOptions = { 
      zoom: 8, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
  } 
 
</script> 
</head> 
<body onload="initialize()"> 
  <div id="map_canvas" style="width:100%; height:100%"></div> 
</body> 
</html>
1.	使用 script 標記來加入 Maps API JavaScript。
2.	咱們建立一個名爲「map_canvas」的 div 元素來承載該地圖。
3.	建立 Javascript 對象常量以保存若干地圖屬性。
4.	編寫 Javascript 函數以建立「map」對象。
5.	咱們從 body 標記的 onload 事件初始化該地圖對象。

載入 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>
http://maps.google.com/maps/api/js 網址指向 Javascript 文件所在的位置,該文件會載入使用第 3 版 Google Maps API 所需的所有符號和定義。您的網頁必須包含指向該網址的 script 標籤。
此標頭中的 <meta> 標籤會指定以下內容:即應當以全屏模式顯示該地圖,且用戶不能調整地圖尺寸。(有關詳細信息,請參見開發移動設備部分。)
請注意,咱們還須要設置 sensor 參數,以指明此應用程序是否使用傳感器肯定用戶的位置。在此示例中,咱們將該參數設爲變量「set_to_true_or_false」,用於強調您必須將該值顯式設爲 true 或 false。
地圖 DOM 元素
<div id="map_canvas" style="width: 100%; height: 100%"></div>
要在網頁上顯示地圖,咱們必須爲其留出一個位置。一般,咱們的作法是建立一個名爲 div 的元素,而後在瀏覽器的文檔對象模型 (DOM) 中獲取此元素的引用。
在上述示例中,咱們定義了名爲「map_canvas」的 <div> 並使用樣式屬性設置其大小。請注意,該尺寸已設置爲「100%」,這將會展開地圖,使之符合移動設備的屏幕尺寸。您可能須要根據瀏覽器的屏幕尺寸和填充區域調整這些值。請注意,地圖老是會根據其中所包含的元素的大小決定其自己的尺寸,所以,您必須始終在 <div> 上顯式設置一個適用的尺寸。
地圖選項
var myLatlng = new google.maps.LatLng(-34.397, 150.644); 
var myOptions = { 
  zoom: 8, 
  center: myLatlng, 
  mapTypeId: google.maps.MapTypeId.ROADMAP 
};
要初始化地圖,咱們須要先建立一個包含地圖初始化變量的 Map options 對象。該對象不是構建出來的,而是以對象常量的形式建立出來的。因爲咱們要將地圖的中心設定爲某一特定的點,所以,咱們還須要建立一個 latlng 值,以保存此位置信息並將其傳遞到地圖的選項中。有關指定位置的詳細信息,請參閱下面的 緯度和經度部分。 
咱們還設置了初始縮放級別,並將 mapTypeId 設置爲 google.maps.MapTypeId.ROADMAP。系統支持如下類型:
•	ROADMAP,用於顯示 Google Maps 默認的普通二維圖塊。
•	SATELLITE,用於顯示拍攝的圖塊。
•	HYBRID,用於同時顯示拍攝的圖塊和突出特徵(道路、城市名)圖塊層。
•	TERRAIN,用於顯示天然地形圖塊,天然地形圖塊中會顯示高度和水體特徵(山脈、河流等)。
與 Google Maps 第 2 版 API 不一樣的是,第 3 版中沒有設置默認地圖類型。您必須明確設置一個初始地圖類型,才能查看相應的圖塊。
google.maps.Map - 基本對象
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
Map 類是表示地圖的 JavaScript 類。此類的對象定義了網頁上的單個地圖。(您能夠建立此類的多個實例,每一個對象都將在網頁上定義一個單獨的地圖。)咱們使用 Javascript new 操做符建立此類的一個新實例。
建立新的地圖實例時,您須要在網頁中指定一個 <div> HTML 元素做爲地圖的容器。HTML 節點是 Javascript document 對象的子對象,並且咱們經過 document.getElementById() 方法得到該元素的引用。
此代碼可定義一個名爲 map 的變量,而後將該變量分配給新的 Map 對象,同時將該變量傳遞到在 myOptions 對象常量內定義的選項中。這些選項將會用於初始化地圖的屬性。Map() 函數稱爲「構造函數」,其定義以下: 
構造函數	說明
google.maps.Map( opts?)	使用 opts 參數中已傳遞的可選參數建立新地圖。
載入地圖
  <body onload="initialize()">
呈現 HTML 網頁時,會擴展文檔對象模型 (DOM),接收任何外部圖像和腳本並將其合併到 document 對象中。爲了確保系統在徹底載入網頁後纔將咱們的地圖添加到網頁上,咱們只會在 HTML 網頁的 <body> 元素收到 onload 事件後,纔會執行用於構建 Map 對象的函數。這樣作能夠避免出現不可預期的行爲,並使咱們能夠對地圖繪製的方式和時間進行更多控制。
body 標籤的 onload 屬性是事件處理程序的一個示例。Google Maps Javascript API 還提供了一組事件,可供您進行處理以肯定狀態變化。有關詳細信息,請參閱地圖事件部分。
查看示例 (map-simple.html)
緯度和經度
咱們還須要一種引用各類地圖位置的方法。在 Google Maps API 中,google.maps.LatLng 對象提供了此類機制。您能夠構建一個 LatLng 對象,以 {緯度, 經度} 的順序傳遞其參數:
  var myLatlng = new google.maps.LatLng(myLatitude, myLongitude)
請注意:將「地址」轉變爲地理地點的過程叫作「地址解析」。此版本的 Google Maps API 可支持地址解析。有關詳細信息,請參見服務部分中的地址解析。
LatLng 對象在 Google Maps API 中用途普遍。例如,google.maps.Marker 對象會在其構造函數中應用 LatLng,並在地圖上所指定的地理位置上添加標記 疊加層。
地圖類型
Google Maps API 中提供了多種地圖類型。除了用戶熟悉的「繪製」道路地圖圖塊,Google Maps API 還可支持其餘地圖類型。這些地圖類型是經過使用 mapTypeId 屬性,在地圖的 Map options 對象中設置的。
Google Maps API 提供瞭如下地圖類型:
•	MapTypeId.ROADMAP,用於顯示默認的道路地圖視圖
•	MapTypeId.SATELLITE,用於顯示 Google 地球衛星圖像
•	MapTypeId.HYBRID,用於同時顯示普通視圖和衛星視圖
•	MapTypeId.TERRAIN,用於根據地形信息顯示實際地圖。 
您能夠經過調用地圖的 setMapTypeId() 方法更改地圖的類型。

用戶界面事件
Google Maps API 中的一些對象旨在對用戶事件(例如鼠標事件或鍵盤事件)做出響應。google.maps.Marker 對象能夠偵聽如下用戶事件,例如:
•	'click'
•	'dblclick'
•	'mouseup'
•	'mousedown'
•	'mouseover'
•	'mouseout'
這些事件可能看上去像是標準 DOM 事件,但實際上倒是 Google Maps API 的一部分。因爲不一樣的瀏覽器可實現不一樣的 DOM 事件模型,所以,Google Maps API 提供了無需處理各類跨瀏覽器特性即可偵聽和響應 DOM 事件的機制。這些事件一般還會在代表某些用戶界面狀態(例如鼠標位置)的事件中傳遞參數。
MVC 狀態更改
MVC 對象一般都有相應的狀態。只要更改了對象的屬性,那麼,API 就會觸發已更改該屬性的事件。例如,當地圖的縮放級別更改後,API 將會觸發地圖上的 zoom_changed 事件。您也能夠經過在 event 命名空間方法中註冊 addListener() 事件處理程序的方式截獲這些狀態更改。
用戶事件和 MVC 狀態更改看上去很類似,但一般狀況下,您應該在代碼中對它們進行不一樣的處理。例如,MVC 事件不在它們的事件中傳遞參數。您可能須要經過調用該對象上相應的 getProperty 方法,檢查在 MVC 狀態更改中更改的屬性。
地圖事件
您可以使用 addListener() 事件處理程序註冊以接收事件通知。該方法有三個參數,一個對象,一個待偵聽事件以及一個在指定事件發生時調用的函數。 
如下代碼可將用戶事件和狀態更改事件進行組合。咱們可將事件處理程序附加到點擊時對地圖執行縮放操做的標記上。咱們還針對「zoom」屬性的更改在地圖中添加了事件處理程序,並在收到 zoom_changed 事件時將地圖移動到澳大利亞北領地的達爾文市:
var map; 
function initialize() { 
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922); 
  var myOptions = { 
    zoom: 4, 
    center: myLatlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
   
  google.maps.event.addListener(map, 'zoom_changed', function() { 
    setTimeout(moveToDarwin, 3000); 
  }); 
   
  var marker = new google.maps.Marker({ 
      position: myLatlng,  
      map: map, 
      title:"Hello World!" 
  }); 
  google.maps.event.addListener(marker, 'click', function() { 
    map.setZoom(8); 
  }); 
} 
   
function moveToDarwin() { 
  var darwin = new google.maps.LatLng(-12.461334, 130.841904); 
  map.setCenter(darwin); 
}
查看示例 (event-simple.html)
請注意:若是您要嘗試檢測視口中的更改,請務必使用特定的 bounds_changed 事件,而不要使用做爲其組成部分的 zoom_changed 和 center_changed 事件。因爲 Google Maps API 會單獨觸發後面的兩個事件,所以,只有在系統強制性地更改了視口後,getBounds() 才能報告有用的結果。若是您想要在此類事件以後實現 getBounds() 方法,請務必偵聽 bounds_changed 事件。
訪問用戶界面事件中的參數
一般狀況下,Google Maps API 第 3 版中的用戶界面事件會傳遞事件參數,您可經過事件偵聽器訪問這些參數,這些參數會註明事件發生時用戶界面所處的狀態。例如,用戶界面 'click' 事件一般傳遞包含 latLng 屬性的 MouseEvent,該屬性指出了地圖上的點擊位置。請注意,這是用戶界面事件所獨有的行爲;MVC 狀態更改不會在它們的事件中傳遞參數。
您能夠訪問事件偵聽器中的事件參數,這與訪問對象屬性的方法同樣。如下示例介紹瞭如何爲地圖添加事件偵聽器,以及如何在用戶點擊地圖時,在所點擊的位置處建立一個標記。
var map; 
function initialize() { 
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922); 
  var myOptions = { 
    zoom: 4, 
    center: myLatlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
   
  google.maps.event.addListener(map, 'click', function(event) { 
    placeMarker(event.latLng); 
  }); 
} 
   
function placeMarker(location) { 
  var clickedLocation = new google.maps.LatLng(location); 
  var marker = new google.maps.Marker({ 
      position: location,  
      map: map 
  }); 
 
  map.setCenter(location); 
}


在事件偵聽器中使用閉包
在執行事件偵聽器時,一般可取的作法是將私有數據和持久性數據附加到對象中。JavaScript 不支持「私有」實例數據,但它支持容許內部函數訪問外部變量的閉包。在事件偵聽器訪問一般不附加到發生事件的對象的變量時,閉包很是有用。
下例在事件偵聽器中使用函數閉包將加密消息分配給一組標記。點擊每一個標記均可以看到加密消息的一部分,該消息並未包含在標記自身內。
var map; 
function initialize() { 
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922); 
  var myOptions = { 
    zoom: 4, 
    center: myLatlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
 
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
 
  // Add 5 markers to the map at random locations 
  var southWest = new google.maps.LatLng(-31.203405,125.244141); 
  var northEast = new google.maps.LatLng(-25.363882,131.044922); 
  var bounds = new google.maps.LatLngBounds(southWest,northEast); 
  map.fitBounds(bounds); 
  var lngSpan = northEast.lng() - southWest.lng(); 
  var latSpan = northEast.lat() - southWest.lat(); 
  for (var i = 0; i < 5; i++) { 
    var location = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), 
        southWest.lng() + lngSpan * Math.random()); 
    var marker = new google.maps.Marker({ 
        position: location,  
        map: map 
    }); 
    var j = i + 1; 
    marker.setTitle(j.toString()); 
    attachSecretMessage(marker, i); 
  } 
} 
 
// The five markers show a secret message when clicked 
// but that message is not within the marker's instance data 
 
function attachSecretMessage(marker, number) { 
  var message = ["This","is","the","secret","message"]; 
  var infowindow = new google.maps.InfoWindow( 
      { content: message[number], 
        size: new google.maps.Size(50,50) 
      }); 
  google.maps.event.addListener(marker, 'click', function() { 
    infowindow.open(map,marker); 
  }); 
}

獲取和設置事件處理程序中的屬性
在系統觸發事件時,Google Maps API 事件系統中的任何 MVC 狀態更改事件都不會傳遞參數(用戶事件確實會傳遞參數,這是能夠檢查到的)。若是您須要檢查有關 MVC 狀態更改的某一屬性,則應當顯式的調用該對象上相應的 getProperty() 方法。在此檢查過程當中,系統會始終檢索 MVC 對象的「當前狀態」,但這一狀態可能不是 MVC 對象在首次觸發相應事件時所處的狀態。
請注意:在對「特定屬性」的狀態更改做出響應的事件處理程序中,顯式設置一個屬性可能會產生不可預期的和/或沒必要要的行爲。例如,設置此類屬性將會觸發新的事件,並且,若是您老是在此事件處理程序中設置屬性,那麼,您最終可能會出現無限循環的狀況。
在如下示例中,咱們會設置一個事件處理程序,使其經過構建顯示縮放級別的信息窗口對縮放事件做出響應。咱們還會檢查地圖是否已徹底縮小,若是是的話,咱們會將地圖放大到縮放級別 17。
var map; 
function initialize() { 
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922); 
  var myOptions = { 
    zoom: 4, 
    center: myLatlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
   
  var zoomLevel; 
  var infowindow = new google.maps.InfoWindow( 
    { content: 'Zoom Level Test', 
        size: new google.maps.Size(50,50), 
        position: myLatlng 
    }); 
  infowindow.open(map); 
     
  google.maps.event.addListener(map, 'zoom_changed', function() { 
    zoomLevel = map.getZoom(); 
    infowindow.setContent("Zoom: " + zoomLevel); 
    if (zoomLevel == 0) { 
      map.setZoom(10); 
    }       
  }); 
}

停用默認用戶界面
有時,您可能但願關閉 API 的默認用戶界面設置。要進行上述操做,請將 Map 的 disableDefaultUI 屬性(在 Map options 對象中)設置爲 true。此屬性可停用 Google Maps API 中全部自動執行的用戶界面行爲。 
如下代碼可完全停用默認用戶界面:
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);                           
}

下面的示例顯示了一個簡單的地圖,其中啓用了位於不一樣位置的全部控件。
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);                           
}

繪製自定義控件
如何繪製控件由您本身決定。通常來說,咱們建議您將全部控件的顯示方式放在一個單獨的 <div> 元素中,以即可以將控件做爲一個單元進行處理。咱們將在下面所示的示例中使用這種設計模式。
設計具備吸引力的控件須要具有一些 CSS 和 DOM 結構方面的知識。如下代碼顯示瞭如何經過一個 <div> 容器、一個承載按鈕輪廓的 <div> 和另外一個承載按鈕內部事項的 <div> 建立一個簡單的控件。
// Create a div to hold the control. 
var controlDiv = document.createElement('DIV'); 
 
// Set CSS styles for the DIV containing the control 
// Setting padding to 5 px will offset the control 
// from the edge of the map 
controlDiv.style.padding = '5px'; 
 
// Set CSS for the control border 
var controlUI = document.createElement('DIV'); 
controlUI.style.backgroundColor = 'white'; 
controlUI.style.borderStyle = 'solid'; 
controlUI.style.borderWidth = '2px'; 
controlUI.style.cursor = 'pointer'; 
controlUI.style.textAlign = 'center'; 
controlUI.title = 'Click to set the map to Home'; 
controlDiv.appendChild(controlUI); 
 
// Set CSS for the control interior 
var controlText = document.createElement('DIV'); 
controlText.style.fontFamily = 'Arial,sans-serif'; 
controlText.style.fontSize = '12px'; 
controlText.style.paddingLeft = '4px'; 
controlText.style.paddingRight = '4px'; 
controlText.innerHTML = 'Home'; 
controlUI.appendChild(controlText);

處理自定義控件的事件
要使控件有用,它必須可以實際完成某些任務。控件的用途由您肯定。控件能夠響應用戶輸入,也能夠響應 Map 的狀態變化。
對於響應用戶輸入,Google Maps API 提供了一個跨瀏覽器的事件處理方法 addDomListener(),它能夠處理瀏覽器的多數支持的 DOM 事件。如下代碼段爲瀏覽器的 'click' 事件添加了一個偵聽器。請注意,此事件是從 DOM 接收的,而不是從地圖。
// Setup the click event listener: simply set the map to 
// center on Chicago 
var chicago = new google.maps.LatLng(41.850033, -87.6500523); 
 
google.maps.event.addDomListener(outer, 'click', function() { 
  map.setCenter(chicago) 
});

定位自定義控件
要在地圖上定位自定義控件,您能夠在 Map 對象的 controls 屬性中將其放在適當位置。此屬性包含一個 google.maps.ControlPosition 數組。您能夠經過將 Node(一般是 <div>)添加至適當 ControlPosition 向地圖中添加自定義控件。(有關這些位置的信息,請參見上面的控件定位。)
每一個 ControlPosition 會存儲一個顯示在該位置的控件的 MVCArray。所以,當您向該位置添加或從中刪除控件時,API 將相應更新控件。
API 按照 index 屬性的順序將控件放在每一個位置,並會首先放置索引值較低的控件。例如,位置 BOTTOM_RIGHT 處的兩個自定義控件將按照此索引順序進行排列,並優先放置索引值較低的控件。默認狀況下,全部自定義控件將在放置完任何 API 默認控件以後進行放置。您能夠經過將控件的 index 屬性設置爲一個負值覆蓋此行爲。請注意,若是但願在放置相同位置的默認 API 控件「以前」放置您的控件,一般只需設置一個索引值。
如下代碼將建立一個新的自定義控件(未顯示其構造函數)並將其添加到地圖中的 TOP_RIGHT 位置。
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); 
 
// Construct your control in whatever manner is appropriate. 
// Generally, your constructor will want access to the 
// DIV on which you'll attach the control UI to the Map. 
var controlDiv = document.createElement('DIV'); 
var myControl = new MyControl(controlDiv); 
 
// We don't really need to set an index value here, but 
// this would be how you do it. Note that we set this 
// value as a property of the DIV itself. 
controlDiv.index = 1; 
 
// Add the control to the map at a designated control position 
// by pushing it on the position's array. This code will 
// implicitly add the control to the DOM, through the Map 
// object. You should not attach the control manually. 
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);

自定義控件示例
下面是一個簡單的控件(儘管不是很實用),其中綜合了上面所示的模式。該控件經過將地圖在某個默認位置居中來響應 DOM 'click' 事件:
var map; 
var chicago = new google.maps.LatLng(41.850033, -87.6500523); 
 
/** 
 * The HomeControl adds a control to the map that simply 
 * returns the user to Chicago. This constructor takes 
 * the control DIV as an argument. 
 */ 
 
function HomeControl(controlDiv, map) { 
 
  // Set CSS styles for the DIV containing the control 
  // Setting padding to 5 px will offset the control 
  // from the edge of the map 
  controlDiv.style.padding = '5px'; 
 
  // Set CSS for the control border 
  var controlUI = document.createElement('DIV'); 
  controlUI.style.backgroundColor = 'white'; 
  controlUI.style.borderStyle = 'solid'; 
  controlUI.style.borderWidth = '2px'; 
  controlUI.style.cursor = 'pointer'; 
  controlUI.style.textAlign = 'center'; 
  controlUI.title = 'Click to set the map to Home'; 
  controlDiv.appendChild(controlUI); 
 
  // Set CSS for the control interior 
  var controlText = document.createElement('DIV'); 
  controlText.style.fontFamily = 'Arial,sans-serif'; 
  controlText.style.fontSize = '12px'; 
  controlText.style.paddingLeft = '4px'; 
  controlText.style.paddingRight = '4px'; 
  controlText.innerHTML = 'Home'; 
  controlUI.appendChild(controlText); 
 
  // Setup the click event listeners: simply set the map to 
  // Chicago 
  google.maps.event.addDomListener(controlUI, 'click', function() { 
    map.setCenter(chicago) 
  }); 
} 
 
function initialize() { 
  var mapDiv = document.getElementById('map_canvas'); 
  var myOptions = { 
    zoom: 12, 
    center: chicago, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
  map = new google.maps.Map(mapDiv, myOptions); 
 
  // Create the DIV to hold the control and 
  // call the HomeControl() constructor passing 
  // in this DIV. 
  var homeControlDiv = document.createElement('DIV'); 
  var homeControl = new HomeControl(homeControlDiv, map); 
 
  homeControlDiv.index = 1; 
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv); 
}

爲控件添加狀態
控件也能夠存儲狀態。下面的示例與前面所示的相似,但該控件包含了一個額外的「Set Home」按鈕,它將控件設置爲顯示一個新首頁位置。爲此,咱們在該控件內建立一個 home_ 屬性以存儲此狀態,併爲該狀態提供了獲取函數和設置函數。
var map; 
var chicago = new google.maps.LatLng(41.850033, -87.6500523); 
 
/** 
 * The HomeControl adds a control to the map that 
 * returns the user to the control's defined home. 
 */ 
 
// Define a property to hold the Home state 
HomeControl.prototype.home_ = null; 
 
// Define setters and getters for this property 
HomeControl.prototype.getHome = function() { 
  return this.home_; 
} 
 
HomeControl.prototype.setHome = function(home) { 
  this.home_ = home; 
} 
 
function HomeControl(map, div, home) { 
 
  // Get the control DIV. We'll attach our control 
  // UI to this DIV. 
  var controlDiv = div; 
 
  // We set up a variable for the 'this' keyword 
  // since we're adding event listeners later 
  // and 'this' will be out of scope. 
  var control = this; 
 
  // Set the home property upon construction 
  control.home_ = home; 
 
  // Set CSS styles for the DIV containing the control 
  // Setting padding to 5 px will offset the control 
  // from the edge of the map 
  controlDiv.style.padding = '5px'; 
 
  // Set CSS for the control border 
  var goHomeUI = document.createElement('DIV'); 
  goHomeUI.title = 'Click to set the map to Home'; 
  controlDiv.appendChild(goHomeUI); 
 
  // Set CSS for the control interior 
  var goHomeText = document.createElement('DIV'); 
  goHomeText.innerHTML = 'Home'; 
  goHomeUI.appendChild(goHomeText); 
   
  // Set CSS for the setHome control border 
  var setHomeUI = document.createElement('DIV'); 
  setHomeUI.title = 'Click to set Home to the current center'; 
  controlDiv.appendChild(setHomeUI); 
 
  // Set CSS for the control interior 
  var setHomeText = document.createElement('DIV'); 
  setHomeText.innerHTML = 'Set Home'; 
  setHomeUI.appendChild(setHomeText); 
 
  // Setup the click event listener for Home: 
  // simply set the map to the control's current home property. 
  google.maps.event.addDomListener(goHomeUI, 'click', function() { 
    var currentHome = control.getHome(); 
    map.setCenter(currentHome); 
  }); 
   
  // Setup the click event listener for Set Home: 
  // Set the control's home to the current Map center. 
  google.maps.event.addDomListener(setHomeUI, 'click', function() { 
    var newHome = map.getCenter(); 
    control.setHome(newHome); 
  }); 
} 
 
function initialize() { 
  var mapDiv = document.getElementById('map_canvas'); 
  var myOptions = { 
    zoom: 12, 
    center: chicago, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
  map = new google.maps.Map(mapDiv, myOptions); 
 
  // Create the DIV to hold the control and 
  // call the HomeControl() constructor passing 
  // in this DIV. 
  var homeControlDiv = document.createElement('DIV'); 
  var homeControl = new HomeControl(map, homeControlDiv, chicago); 
 
  homeControlDiv.index = 1; 
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);

添加疊加層
疊加層一般在構造時添加到地圖中。全部疊加層都會定義構造中所用的 Options 對象,以指定應顯示疊加層的地圖。您也可使用疊加層的 setMap() 方法,將其傳遞給要添加疊加層的地圖,從而直接在地圖上添加疊加層。
  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);  
刪除疊加層
要從地圖上刪除疊加層,可調用疊加層的 setMap() 方法,傳遞 null。請注意,調用此方法不會刪除疊加層,而只是從地圖上刪除疊加層。若是您要刪除疊加層,則應當從地圖上刪除疊加層,而後將疊加層設置爲 null。
若是您要管理一組疊加層,則應當建立一個數組以存儲這些疊加層。使用數組後,只要您須要刪除疊加層,就能夠對數組中的每一個疊加層調用 setMap()。(請注意,與第 2 版不一樣,該版本中未提供 clearOverlays() 方法。對於跟蹤疊加層並在不須要時將其從地圖中刪除的任務,您須要本身執行。)要刪除疊加層,您能夠從地圖上刪除疊加層並將數組的 length 設置爲 0,但此操做會刪除對疊加層的全部引用。
下面示例的效果是點擊地圖時將標記放在地圖上,而後將標記放入數組中。疊加層稍後能夠刪除、顯示或刪除:
var map; 
var markersArray = []; 
 
function initialize() { 
  var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157); 
  var mapOptions = { 
    zoom: 12, 
    center: haightAshbury, 
    mapTypeId: google.maps.MapTypeId.TERRAIN 
  }; 
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
 
  google.maps.event.addListener(map, 'click', function(event) { 
    addMarker(event.latLng); 
  }); 
} 
   
function addMarker(location) { 
  marker = new google.maps.Marker({ 
    position: location, 
    map: map 
  }); 
  markersArray.push(marker); 
} 
 
// 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; 
  } 
}

標記
標記用於標識地圖上的位置。默認狀況下,標記使用的是標準圖標,但您能夠在標記的構造函數中設置一個自定義圖標,或者經過對標記調用 setIcon() 設置一個自定義圖標。google.maps.Marker 構造函數採用的是用於指定標記初始屬性的一個 Marker options 對象常量。如下字段特別重要,一般是在您構建標記時進行設置的:
•	position(必需),用於指定標識標記初始位置的 LatLng。
•	map(可選),用於指定要在其上設置標記的 Map 對象。
請注意,您應在 Marker 構造函數指定要爲哪一個地圖添加標記。若是您不指定此參數,那麼,您只能建立標記,而沒法將其附加到地圖上(或在地圖上顯示)。稍後,您能夠經過調用標記的 setMap() 方法添加該標記。要刪除標記,請調用將 null 做爲參數傳遞的 setMap() 方法。
標記設計爲可交互。例如,默認狀況下它們接收 'click' 事件,經常使用於在事件偵聽器中打開信息窗口。
如下示例介紹瞭如何將一個簡單的標記添加到澳大利亞中心區域的烏魯魯的地圖上: 
  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!" 
  });   
此 Marker 標題將會以提示的形式顯示。
若是您不想在標記的構造函數中傳遞任何 Marker options,那麼,請在構造函數的最後一個參數中傳遞一個空對象 {}。

圖標
標記能夠定義要顯示的圖標,從而取代默認的圖標。定義圖標的過程當中包含設置若干可定義標記視覺行爲的屬性。
簡單圖標
就最基本的狀況而言,只需將標記的 icon 屬性設置爲某一圖像的網址,圖標即可指明要使用的圖像(而非默認的 Google Maps 圖釘圖標)。在這種狀況下,Google Maps API 將會自動調整圖標的大小。
在如下示例中,咱們會建立一個圖標,用於標示澳大利亞悉尼的邦迪海灘的位置:
function initialize() { 
  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 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 
  }); 
}

複雜圖標
較爲複雜的圖標可用於指定複雜的形狀(表示用戶可點擊的區域)、添加陰影圖像,以及指定這些形狀與其餘疊加層在顯示時應採用的「堆疊順序」。以這種方式指定的圖標應當將本身的 icon 屬性和 shadow 屬性設置爲 MarkerImage 類型的對象。
陰影圖像一般應該和主圖像成 45 度夾角(向右上方傾斜),而且陰影圖像的左下角應與圖標圖像的左下角對齊。陰影圖像應是半透明的 24 位 PNG 圖像,這樣圖像邊界即可以在地圖上正確顯示。
MarkerImage 對象不只能夠定義圖像,還可定義圖標的 size、圖標的 origin(例如,在您所需的圖像取自一張較大的拼合圖像時)以及圖標熱點所應定位的 anchor(取決於原點)。
如下示例介紹瞭如何建立複雜的標記,以表示澳大利亞新南威爾士的悉尼附近的海灘。請注意,應當將 anchor 設置爲 (0,32),從而與旗杆的基座相對應。
function initialize() { 
  var myOptions = { 
    zoom: 10, 
    center: new google.maps.LatLng(-33.9, 151.2), 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
  } 
  var map = new google.maps.Map(document.getElementById("map_canvas"), 
                                myOptions); 
 
  setMarkers(map, beaches); 
} 
 
/** 
 * Data for the markers consisting of a name, a LatLng and a zIndex for 
 * the order in which these markers should display on top of each 
 * other. 
 */ 
var beaches = [ 
  ['Bondi Beach', -33.890542, 151.274856, 4], 
  ['Coogee Beach', -33.923036, 151.259052, 5], 
  ['Cronulla Beach', -34.028249, 151.157507, 3], 
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], 
  ['Maroubra Beach', -33.950198, 151.259302, 1] 
]; 
 
function setMarkers(map, locations) { 
  // Add markers to the map 
 
  // Marker sizes are expressed as a Size of X,Y 
  // where the origin of the image (0,0) is located 
  // in the top left of the image. 
 
  // Origins, anchor positions and coordinates of the marker 
  // increase in the X direction to the right and in 
  // the Y direction down. 
  var image = new google.maps.MarkerImage('images/beachflag.png', 
      // This marker is 20 pixels wide by 32 pixels tall. 
      new google.maps.Size(20, 32), 
      // The origin for this image is 0,0. 
      new google.maps.Point(0,0), 
      // The anchor for this image is the base of the flagpole at 0,32. 
      new google.maps.Point(0, 32)); 
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png', 
      // The shadow image is larger in the horizontal dimension 
      // while the position and offset are the same as for the main image. 
      new google.maps.Size(37, 32), 
      new google.maps.Point(0,0), 
      new google.maps.Point(0, 32)); 
      // Shapes define the clickable region of the icon. 
      // The type defines an HTML <area> element 'poly' which 
      // traces out a polygon as a series of X,Y points. The final 
      // coordinate closes the poly by connecting to the first 
      // coordinate. 
  var shape = { 
      coord: [1, 1, 1, 20, 18, 20, 18 , 1], 
      type: 'poly' 
  }; 
  for (var i = 0; i < locations.length; i++) { 
    var beach = locations[i]; 
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]); 
    var marker = new google.maps.Marker({ 
        position: myLatLng, 
        map: map, 
        shadow: shadow, 
        icon: image, 
        shape: shape, 
        title: beach[0], 
        zIndex: beach[3] 
    }); 
  } 
}

地面疊加層
多邊形在表示不規則的區域時頗有用,但不能顯示圖片。若是要在地圖上放置一幅圖片,可使用 GroundOverlay 對象。 GroundOverlay 的構造函數採用圖片的網址和 LatLngBounds 做爲參數。圖片將渲染在地圖上的指定邊界內,並與地圖的投影一致。
下面的示例將新澤西州紐瓦克的一幅老地圖做爲疊加層放在地圖上:
var newark = new google.maps.LatLng(40.740, -74.18); 
var imageBounds = new google.maps.LatLngBounds( 
    new google.maps.LatLng(40.716216,-74.213393), 
    new google.maps.LatLng(40.765641,-74.139235)); 
 
var myOptions = { 
  zoom: 13, 
  center: newark, 
  mapTypeId: google.maps.MapTypeId.ROADMAP 
} 
 
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
 
var oldmap = new google.maps.GroundOverlay( 
    "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", 
    imageBounds); 
oldmap.setMap(map);

狀態代碼
status 代碼可能返回下面的某個值:
•	google.maps.GeocoderStatus.OK 表示地址解析成功。
•	google.maps.GeocoderStatus.ZERO_RESULTS 表示地址解析成功,但未返回結果。若是地址解析過程當中傳遞的偏遠位置 address 或 latng 並不存在,則會出現 種狀況。
•	google.maps.GeocoderStatus.OVER_QUERY_LIMIT 表示您超出了配額。
•	google.maps.GeocoderStatus.REQUEST_DENIED 表示因爲某種緣由拒絕了您的請求。 
•	google.maps.GeocoderStatus.INVALID_REQUEST 一般表示缺乏查詢參數(address 或 latLng)。
在此示例中,咱們對一個地址進行地址解析,並根據返回的緯度/經度值放置標記。請注意,處理程序以匿名函數顯式聲明的形式傳遞。
  var geocoder; 
  var map; 
  function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 
    var myOptions = { 
      zoom: 8, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
  } 
 
  function codeAddress() { 
    var address = document.getElementById("address").value; 
    if (geocoder) { 
      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); 
        } 
      }); 
    } 
  } 
 
<body onload="initialize()"> 
 <div id="map_canvas" style="width: 320px; height: 480px;"></div> 
  <div> 
    <input id="address" type="textbox" value="Sydney, NSW"> 
    <input type="button" value="Encode" onclick="codeAddress()"> 
  </div> 
</body>

建立地圖和用戶界面
設置完後端功能以後,接下來就能夠建立地圖和用戶界面功能。若是您從未建立過 Google Maps,請先嚐試建立文檔中介紹的一些基本示例,從而確保您掌握了建立地圖的基礎知識。 
建立標記和信息窗口
建立地圖並使地圖居中,而後,爲該地圖分配一個 click 偵聽器。在偵聽器的回調函數中,在點擊過的座標處建立一個標記,並在發送至構造函數的 GMarkerOptions 對象中將 draggable 屬性設置爲 "true"。而後,爲該標記分配一個 click 偵聽器,用於在標記上方彈出一個信息窗口。此信息窗口含有某一表單的 HTML 代碼,該表單包含幾個文本字段、一個下拉列表及一個保存按鈕。以下所述,每一個表單輸入項都對應一個 ID,並且,保存按鈕具備一個 onclick 偵聽器,用於調用 saveData 函數。 
保存數據
在信息窗口按鈕所調用的 saveData 函數中,您能夠執行如下操做: 
•	保存標記座標的值和全部表單元素(若有須要,請轉義爲易於訪問的網址)。 
•	將 PHP 文件名、參數及其相應的值合在一塊兒,造成一個網址。 
•	將該網址做爲 GDownloadUrl 的第一個參數進行傳遞,這個由 API 提供的函數會封裝 XMLHTTPRequest 對象,該對象能讓您經過 Javascript 檢索各類文件(一般爲 XML 格式)。GDownloadUrl 回調函數將會爲您提供相應網址的內容及狀態代碼。 
•	檢查並確保返回的狀態代碼爲 200。這表示已成功地檢索到該文件,咱們能夠繼續進行處理了。 
•	檢查返回的數據字符串的長度,空數據文件表示未輸出任何錯誤的字符串。若是字符串長度接近零,您能夠關閉信息窗口,而後輸出操做已成功的消息。 
執行以上全部操做的 HTML 文件以下所示 (phpsqlinfo_add.html): 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title>Google Maps JavaScript API Example: Simple Map</title>
    <script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxTPZYElJSBeBUeMSX5xXgq6lLjHthSAk20WnZ_iuuzhMt60X_ukms-AUg"
            type="text/javascript"></script>
    <script type="text/javascript">

    var marker;

    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);

        GEvent.addListener(map, "click", function(overlay, latlng) {
          if (latlng) {
            marker = new GMarker(latlng, {draggable:true});
            GEvent.addListener(marker, "click", function() {
              var html = "<table>" +
                         "<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
                         "<tr><td>Address:</td> <td><input type='text' id='address'/></td> </tr>" +
                         "<tr><td>Type:</td> <td><select id='type'>" +
                         "<option value='bar' SELECTED>bar</option>" +
                         "<option value='restaurant'>restaurant</option>" +
                         "</select> </td></tr>" +
                         "<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";

              marker.openInfoWindow(html);
            });
            map.addOverlay(marker);
          }
        });

      }
    }

    function saveData() {
      var name = escape(document.getElementById("name").value);
      var address = escape(document.getElementById("address").value);
      var type = document.getElementById("type").value;
      var latlng = marker.getLatLng();
      var lat = latlng.lat();
      var lng = latlng.lng();

      var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
                "&type=" + type + "&lat=" + lat + "&lng=" + lng;
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length <= 1) {
          marker.closeInfoWindow();
          document.getElementById("message").innerHTML = "Location added.";
        }
      });
    }
    </script>

  </head>

  <body onload="initialize()" onunload="GUnload()">
    <div id="map_canvas" style="width: 500px; height: 300px"></div>
    <div id="message"></div>
  </body>

</html>
在打開信息窗口時,地圖應以下所示:

相關文章
相關標籤/搜索