[Google Map]我的第一張地圖
七月 10, 2008
要使用Google Map你只要會一點HTML和Javascript就可以了。
申請 Google Maps API Key
如果你只是要在自己的電腦上測試可以先跳過這個步驟。
但是當你要把寫好的程式放到網站時就一定要申請不然google不給用。
申請API Key的網址:Sign Up for the Google Maps API
打勾(表示你同意Google所訂的條款)輸入你的網站URL再按「Generate API Key」就會產生專屬的key。
若使用錯誤的key會顯示「此網站上使用的Google地圖API機碼已由另一個網站註用。您可以至http://code.google.com/apis/maps/ 為此網站產生新的機碼。」
網頁編碼要用 UTF-8
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
基本程式
AJAX 版(執行範例)
<!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 | Horn Network</title>
<script src="http://maps.google.com/jsapi?key=_KEY_"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
google.load("maps", "2.x");
google.setOnLoadCallback(initialize);
var map = null;
function initialize() {
// 檢查瀏覽器是否可使用 Google Map API
if ( GBrowserIsCompatible() ) {
map = new google.maps.Map2(document.getElementById('map'));
// 設定地圖中心點
map.setCenter(new GLatLng(25.036772,121.520269), 12);
} // if
else {
alert('您的瀏覽器不支援Google Map');
} // else
}
//]]>
</script>
</head>
<body onunload="GUnload()">
<div id="map" style="width:500px; height:500px"></div>
<small><a href="http://klcin.tw/net">Horn Network</a></small>
</body>
</html>
舊版(參考:The 『Hello, World』 of Google Maps)
<!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 | Horn Network</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=_KEY_"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function initialize() {
// 檢查瀏覽器是否可使用 Google Map API
if ( GBrowserIsCompatible() ) {
var map = new GMap2(document.getElementById("map"));
// 設定地圖中心點
map.setCenter(new GLatLng(25.036772,121.520269), 12);
} // if
else {
alert('您的瀏覽器不支援Google Map');
} // else
}
//]]>
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map" style="width:500px; height:500px"></div>
<small><a href="http://klcin.tw/net">Horn Network</a></small>
</body>
</html>
延伸閱讀: