ASP.NET調用V3版本的Google Maps API

寫在最前面

早就聽說過Google Maps API了,但一直沒用過,今天在CodeProject上看到了這篇關於Google Maps API(V3版本)使用的文章,覺得很容易上手,就將他翻譯下來了,相信對初學者會有大的幫助。譯文允許轉載,但請在頁面明顯處標明以下信息,且保留完整原文鏈接地址和譯文鏈接地址,謝謝合作!

英文原文:Google Maps API V3 for ASP.NET

譯文出處:青藤園

譯文作者:王國峯

譯文鏈接:ASP.NET中使用Google Maps API V3【譯】

簡介

Google Maps爲我們提供了一種非常靈活的方式來使用它的地圖服務。我們可以在Web應用程序中通過調用Google Maps API來爲我們的用戶提供方位信息、地理位置信息以及其他類型的東西。儘管已經有很多文章介紹了Google Maps API的使用方法,但這次我要介紹的是最新V3版本的Google Maps API。在這篇文章中,我們將會看到一些使用Google Maps的常見技術。爲了能更好的理解下面的示例代碼,你需要了解Javascript和C#的基本知識。

你的第一個Google Maps

在Google Maps API的早期版本中,我們需要將自己的web應用程序註冊至Google,從而獲取一個API Key。然而隨着新版本的發佈,Google Maps的註冊機制已經被淘汰了,但是最近Google又提出了一些使用地圖的限制,你可以通過下面的鏈接獲取Google Maps API的使用方法和一些使用條款:http://code.google.com/apis/maps/documentation/javascript/usage.html#usage_limits。現在我們就開始在自己的網站下創建一個Google Maps地圖示例,下面的一行代碼是用來連接Google Maps API服務的:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"> 
</script> 

然後你可以用下面的代碼來創建一個簡單的地圖:

functionInitializeMap()  
{
   varlatlng = newgoogle.maps.LatLng(-34.397, 150.644);  
   varmyOptions = {zoom: 8,  center: latlng,  mapTypeId: google.maps.MapTypeId.ROADMAP};
   varmap = newgoogle.maps.Map(document.getElementById("map"), myOptions);
}
   window.onload = InitializeMap;

Google Maps 設置選項

在上面的例子中,我們使用了一個Map類,並設置了一個HTML ID作爲參數。現在我們來更深入一點,一起來看看下面的地圖選項:

    Codefunctioninitialize() {
      varlatlng = newgoogle.maps.LatLng(-34.397, 150.644);
      varoptions =  
      {  
      zoom: 3,  
      center: newgoogle.maps.LatLng(37.09, -95.71),  
      mapTypeId: google.maps.MapTypeId.ROADMAP,  
      mapTypeControl: true,  
      mapTypeControlOptions:  
      {  
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,  
      poistion: google.maps.ControlPosition.TOP_RIGHT,  
      mapTypeIds: [google.maps.MapTypeId.ROADMAP,  
        google.maps.MapTypeId.TERRAIN,  
        google.maps.MapTypeId.HYBRID,  
        google.maps.MapTypeId.SATELLITE]  
      },  
      navigationControl: true,  
      navigationControlOptions:  
      {  
        style: google.maps.NavigationControlStyle.ZOOM_PAN  
      },  
      scaleControl: true,  
      disableDoubleClickZoom: truefalse,  
      streetViewControl: true,  
      draggableCursor: 'move' 
      };  
      varmap = newgoogle.maps.Map(document.getElementById("map"), options);  
      }  
      window.onload = initialize;

上面的例子中,我們應用了地圖的所有屬性,你可以根據需要來選擇使用它們。

Map類的屬性說明如下表所示

屬性
MapTypeControl:true/false mapTypeControlOptions
屬性
style
1
2
3
DEFAULT
HORIZONTAL_BAR
DROPDOWN_MENU
position
mapTypeIds
navigationControl:true/false navigationControlOptions
屬性
Position
style
scaleControl:true/false scaleControlOptions: 和navigationControl有一樣的屬性 (position, style) 方法也一樣.
disableDoubleClickZoom: true/false
 
scrollwheel: true/false
 
draggable: true/false
 
streetViewControl: true/false
 

Map Maker(地圖標記)

Maker類提供了這樣一個選項,爲用戶指定的位置顯示一個標記,在我們的應用中地圖標記是十分常用的,下面的代碼將告訴大家如何創建一個簡單的地圖標記:

    varmarker = newgoogle.maps.Marker  
    (  
    {  
        position: newgoogle.maps.LatLng(-34.397, 150.644),  
        map: map,  
        title: 'Click me' 
    }  
    ); 

Info Window(信息窗口)

我們已經在地圖上某個位置加了標記,也爲標記添加onclick了事件,點擊可以彈出一個窗口來顯示該地點的詳細信息。我們可以按照下面的代碼來創建信息窗口:

varinfowindow = newgoogle.maps.InfoWindow({  
        content: 'Location info:  
        Country Name:  
        LatLng:'  
        });  
        google.maps.event.addListener(marker, 'click', function() {  
        // 打開窗口  
        infowindow.open(map, marker);  
    }); 


將它們結合起來的代碼如下:

Codevarmap;  
    functioninitialize() {  
        varlatlng = newgoogle.maps.LatLng(-34.397, 150.644);  
        varmyOptions = {  
            zoom: 8,  
            center: latlng, 
            mapTypeId: google.maps.MapTypeId.ROADMAP  
        };  
        map = newgoogle.maps.Map(document.getElementById("map"), myOptions); 
         varmarker = newgoogle.maps.Marker 
         (  
         {  
            position: newgoogle.maps.LatLng(-34.397, 150.644),   
            map: map,  
            title: 'Click me' 
         }  
         );  
         varinfowindow = newgoogle.maps.InfoWindow({  
            content: 'Location info:  Country Name:  LatLng:'  
         });  
         google.maps.event.addListener(marker, 'click', function() {  
         // Calling the open method of the infoWindow  
         infowindow.open(map, marker);  
         });   
     }  
     window.onload = initialize; 


利用上面的代碼,我們將會在頁面上創建一張地圖,然後定位用戶所在的區域,在這個區域加上標記,並且彈出一個顯示位置信息的窗口。

Multiple Makers(多標記)

有些時候,我們可以要在地圖上處理多個標記,那麼我們就可以用下面代碼來實現:

Codefunctionmarkicons() {  
        InitializeMap();  
        varltlng = [];  
        ltlng.push(newgoogle.maps.LatLng(40.756, -73.986));  
        ltlng.push(newgoogle.maps.LatLng(37.775, -122.419));  
        ltlng.push(newgoogle.maps.LatLng(47.620, -122.347)); 
        ltlng.push(newgoogle.maps.LatLng(-22.933, -43.184));  
        for(vari = 0; i <= ltlng.length;i++) 
        {  
            marker = newgoogle.maps.Marker({  
            map: map,  
            position: ltlng[i]  
            });  
            (function(i, marker) {  
                google.maps.event.addListener(marker, 'click',function() {  
                if(!infowindow) {  
                    infowindow = newgoogle.maps.InfoWindow();  
                }  
                infowindow.setContent("Message" + i); 
                infowindow.open(map, marker);  
                });  
            })(i, marker);  
        }  
     } 

路線說明

一個最有用的特性之一是Google Maps API可以爲任何指定的位置提供詳細的路線說明,實現代碼如下:

    CodevardirectionsDisplay;  
    vardirectionsService = newgoogle.maps.DirectionsService();  
    functionInitializeMap() {  
        directionsDisplay = newgoogle.maps.DirectionsRenderer();  
        varlatlng = newgoogle.maps.LatLng(-34.397, 150.644);  
        varmyOptions =  
        {  
            zoom: 8,   
            center: latlng,  
            mapTypeId: google.maps.MapTypeId.ROADMAP  
        };  
        varmap = newgoogle.maps.Map(document.getElementById("map"), myOptions);  
        directionsDisplay.setMap(map);  
        directionsDisplay.setPanel(document.getElementById('directionpanel'));  
        varcontrol = document.getElementById('control');  control.style.display = 'block';  
     }  
     calcRoute() {  
        varstart = document.getElementById('startvalue').value;  
        varend = document.getElementById('endvalue').value;  
        varrequest = {  
            origin: start,  
            destination: end,   
            travelMode: google.maps.DirectionsTravelMode.DRIVING  
        };  
        directionsService.route(request, (response, status) {  
            if(status== google.maps.DirectionsStatus.OK) {  
                directionsDisplay.setDirections(response);  
            }  
        });   
     }  
     functionwindow.onload = InitializeMap;


Layers

Google Maps API爲你提供了多層的選項,其中有一個是自行車層。通過自行車層,可以爲一些特別的位置顯示自行車路線。下面的代碼是讓你在地圖上添加自行車層:

Codevarmap  
    functionInitializeMap() {  
        varlatlng = newgoogle.maps.LatLng(-34.397, 150.644);  
        varmyOptions = {  zoom: 8,  center: latlng,  mapTypeId: google.maps.MapTypeId.ROADMAP  };  
        map = newgoogle.maps.Map(document.getElementById("map"), myOptions);  
    }  
    window.onload = InitializeMap;  
    varbikeLayer = newgoogle.maps.BicyclingLayer();  
    bikeLayer.setMap(map);


Geocoding

到目前爲止,我們已經學習創建Google地圖的基本思想,同時也學習瞭如何顯示位置相關的信息。下面我們來看看用戶是如何來計算位置的,Geocoding可以計算出指定區域的經度和緯度,下面的代碼就告訴你如何利用API計算某個位置的經度和緯度的:

Codegeocoder.geocode({ 'address': address }, function(results, status) {  
        if(status== google.maps.GeocoderStatus.OK) {  
            map.setCenter(results[0].geometry.location);  
            varmarker = newgoogle.maps.Marker({   
                map: map,  
                position: results[0].geometry.  
            });  
         }  
         else{  
            alert("Geocode was not successful for the following reason: " + status);  
         }  
      }); 


Geocoding C#

同樣我們可以利用C#代碼來計算位置:

CodepublicstaticCoordinate GetCoordinates(string region)  
{   
    using (varclient = newWebClient())  
    {  
        string uri = "http://maps.google.com/maps/geo?q='" + region +   
                    "'&output=csv&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1" +  
                    "-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA";  
        string[] geocodeInfo = client.DownloadString(uri).Split(',');  
        returnnewpublicstruct Coordinate  
            {  privatedoublelat;  
            private 


Reverse Geocoding

顧名思義,這個是Geocoding的反操作,我們可以根據經度和緯度來找出該位置的名稱。代碼如下:

Codevarmap;  
vargeocoder;  
functionInitializeMap() {  
    varlatlng = newgoogle.maps.LatLng(-34.397, 150.644);  
    myOptions =  
    {  
        zoom: 8,  
        center: latlng,  
        mapTypeId: google.maps.MapTypeId.ROADMAP,  
        disableDefaultUI: true 
     };  
     map = newgoogle.maps.Map(document"), myOptions);
}  
functionFindLocaiton() {  
    geocoder = newgoogle.maps.Geocoder();  
    InitializeMap();  
    varaddress = document.getElementById("addressinput").value;  
    geocoder.geocode({ 'address': address }, function(results,


Reverse Geocoding in C#

同樣用C#也可以實現Reverse Geocoding操作:

CodestaticstringbaseUri =  
"http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}
&sensor=falsestringlocation = string.Empty;  
publicstaticvoidRetrieveFormatedAddress(stringlat, stringlng)  
{  
    requestUri = string.Format(baseUri, lat, lng);  
    using(WebClient wc = newWebClient())  
    {  
        stringinxmlElm.Descendants() where  
        elm.Name == "status


總結

在這篇文章,我嘗試將V3版本的Google Maps API中的最基本和最常用的功能解說清楚。希望這篇文章能幫你順利完成任務。然後,API中還有很多我沒有討論到的,我將嘗試在今後的文章中來討論。當然希望能得到大家的點評和反饋。

源碼下載:http://files.cnblogs.com/sxwgf/GMAP.zip

原文:http://www.cnblogs.com/jz1108/archive/2011/10/21/2220574.html

轉自:http://developer.51cto.com/art/201112/305646.htm

發佈了11 篇原創文章 · 獲贊 7 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章