Google Maps API簡易教程(一)
一、API Key
使用Google API,必須要從Google 那里獲取一個免費(fèi)的API 鍵。獲取過程如下:
(1)用google賬戶登陸https://code.google.com/apis/console/,點擊“Create Project”按鈕,
(2)在服務(wù)列表中,找到Google Maps API v3,點擊off,使其處于on的狀態(tài)。
(3)點擊左邊菜單的"API Access",它將詢問你創(chuàng)建一個OAuth 2.0 client id(簡單應(yīng)用不必)
(4)在下一屏幕中,將會顯示API key的相關(guān)信息。
備注:保存好API key!(在所有Google Maps APP中必須使用)
二、創(chuàng)建一個基本的Google Map
為了簡單起見,下面創(chuàng)建一個以英國倫敦為中心的Google Map。相關(guān)代碼如下:
- <!DOCTYPE html>
- <html>
- <head>
- <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
- </script>
- <script>
- function initialize()
- {
- var mapProp = {
- center:new google.maps.LatLng(51.508742,-0.120850),
- zoom:5,
- mapTypeId:google.maps.MapTypeId.ROADMAP
- };
- var map=new google.maps.Map(document.getElementById("googleMap")
- ,mapProp);
- }
- google.maps.event.addDomListener(window, 'load', initialize);
- </script>
- </head>
- <body>
- <div id="googleMap" style="width:500px;height:380px;"></div>
- </body>
- </html>
備注:script中的key為上一節(jié)注冊的API key。
三、Google Maps-Overlays
Overlays是地圖上的對象,對應(yīng)著相關(guān)的經(jīng)度/維度坐標(biāo)。比較常用的有以下幾種:
.Marker-地圖上單個位置。
.Polyline-地圖上一系列直線。
.Polygon-地圖上一系列直線,并且處于封閉的形狀。
.Circle 和 Rectangle。
.info Windows-地圖上,上升氣球里顯示內(nèi)容。
(1)加入一個Marker
Marker構(gòu)造函數(shù)創(chuàng)建一個標(biāo)簽(注意:必須先設(shè)置位置屬性)。
接著,使用setMap()方法加入marker到map中。
代碼如下:
- var marker=new google.maps.Marker({
- position:myCenter,
- });
- marker.setMap(map);
(2)使Marker動起來
代碼如下:
- marker=new google.maps.Marker({
- position:myCenter,
- animation:google.maps.Animation.BOUNCE
- });
- marker.setMap(map);
(3)Google Maps-Polyline
Polyline是通過一系列排好序的坐標(biāo)的線。它支持一下屬性:
.path-具體化線的幾個經(jīng)度/緯度坐標(biāo)。
.strokeColor-為線設(shè)置一個16進(jìn)制的顏色值。
.strokeOpacity-為線設(shè)置透明度(值介入0.0和1.0之間)
.strokeWeight-具體化線的權(quán)重。
.editable-定義用戶是否可編輯改線。
代碼如下:
- var myTrip = [stavanger,amsterdam,london];
- var flightPath = new google.maps.Polyline({
- path:myTrip,
- strokeColor:"#0000FF",
- strokeOpacity:0.8,
- strokeWeight:2
- });
(4)Circle的用法
circle支持如下屬性:
.center-circle的中心。
.radius-具體圓的半徑,以米為單位。
.strokeColor-為環(huán)繞圓的線設(shè)置一個16進(jìn)制的顏色。
.strokeOpacity-為環(huán)繞圓的線設(shè)置透明度。
.strokeWeight-為環(huán)繞圓的線設(shè)置權(quán)重,單位像素。
.fillColor-為圓的內(nèi)部區(qū)域設(shè)置一個16進(jìn)制顏色值。
.fillOpacity-為圓的內(nèi)部填充顏色設(shè)置透明度。
.editable-解釋同上。
代碼如下:
- var myCity = new google.maps.Circle({
- center:amsterdam,
- radius:20000,
- strokeColor:"#0000FF",
- strokeOpacity:0.8,
- strokeWeight:2,
- fillColor:"#0000FF",
- fillOpacity:0.4
- });
(5)InfoWindow的使用
InfoWindow是為Marker對象顯示相關(guān)文本信息:
例子代碼如下:
- var infowindow = new google.maps.InfoWindow({
- content:"Hello World!"
- });
- infowindow.open(map,marker);
原文鏈接:http://www.cnblogs.com/williamcai/archive/2013/02/27/Technical_enthusiasts.html