ASP.NET調(diào)用V3版本的Google Maps API
寫在最前面
早就聽說過Google Maps API了,但一直沒用過,今天在CodeProject上看到了這篇關(guān)于Google Maps API(V3版本)使用的文章,覺得很容易上手,就將他翻譯下來了,相信對(duì)初學(xué)者會(huì)有大的幫助。譯文允許轉(zhuǎn)載,但請(qǐng)?jiān)陧撁婷黠@處標(biāo)明以下信息,且保留完整原文鏈接地址和譯文鏈接地址,謝謝合作!
英文原文:Google Maps API V3 for ASP.NET
譯文出處:青藤園
譯文作者:王國峰
譯文鏈接:ASP.NET中使用Google Maps API V3【譯】
簡(jiǎn)介
Google Maps為我們提供了一種非常靈活的方式來使用它的地圖服務(wù)。我們可以在Web應(yīng)用程序中通過調(diào)用Google Maps API來為我們的用戶提供方位信息、地理位置信息以及其他類型的東西。盡管已經(jīng)有很多文章介紹了Google Maps API的使用方法,但這次我要介紹的是最新V3版本的Google Maps API。在這篇文章中,我們將會(huì)看到一些使用Google Maps的常見技術(shù)。為了能更好的理解下面的示例代碼,你需要了解Javascript和C#的基本知識(shí)。
你的第一個(gè)Google Maps
在Google Maps API的早期版本中,我們需要將自己的web應(yīng)用程序注冊(cè)至Google,從而獲取一個(gè)API Key。然而隨著新版本的發(fā)布,Google Maps的注冊(cè)機(jī)制已經(jīng)被淘汰了,但是最近Google又提出了一些使用地圖的限制,你可以通過下面的鏈接獲取Google Maps API的使用方法和一些使用條款:http://code.google.com/apis/maps/documentation/javascript/usage.html#usage_limits?,F(xiàn)在我們就開始在自己的網(wǎng)站下創(chuàng)建一個(gè)Google Maps地圖示例,下面的一行代碼是用來連接Google Maps API服務(wù)的:
- <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false">
 - </script>
 
然后你可以用下面的代碼來創(chuàng)建一個(gè)簡(jiǎn)單的地圖:
- 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 設(shè)置選項(xiàng)
在上面的例子中,我們使用了一個(gè)Map類,并設(shè)置了一個(gè)HTML ID作為參數(shù)?,F(xiàn)在我們來更深入一點(diǎn),一起來看看下面的地圖選項(xiàng):
- 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;
 
上面的例子中,我們應(yīng)用了地圖的所有屬性,你可以根據(jù)需要來選擇使用它們。

Map類的屬性說明如下表所示
| 屬性 | 類 | ||||||||||||||
MapTypeControl:true/false | 
            mapTypeControlOptions
            
  | 
        ||||||||||||||
navigationControl:true/false | 
            navigationControlOptions
            
  | 
        ||||||||||||||
scaleControl:true/false | 
            scaleControlOptions: 和navigationControl有一樣的屬性 (position, style) 方法也一樣. | 
        ||||||||||||||
disableDoubleClickZoom: true/false | 
            |||||||||||||||
scrollwheel: true/false | 
            |||||||||||||||
draggable: true/false | 
            |||||||||||||||
streetViewControl: true/false | 
            
Map Maker(地圖標(biāo)記)
Maker類提供了這樣一個(gè)選項(xiàng),為用戶指定的位置顯示一個(gè)標(biāo)記,在我們的應(yīng)用中地圖標(biāo)記是十分常用的,下面的代碼將告訴大家如何創(chuàng)建一個(gè)簡(jiǎn)單的地圖標(biāo)記:
- varmarker = newgoogle.maps.Marker
 - (
 - {
 - position: newgoogle.maps.LatLng(-34.397, 150.644),
 - map: map,
 - title: 'Click me'
 - }
 - );
 

Info Window(信息窗口)
我們已經(jīng)在地圖上某個(gè)位置加了標(biāo)記,也為標(biāo)記添加onclick了事件,點(diǎn)擊可以彈出一個(gè)窗口來顯示該地點(diǎn)的詳細(xì)信息。我們可以按照下面的代碼來創(chuàng)建信息窗口:
- varinfowindow = newgoogle.maps.InfoWindow({
 - content: 'Location info:
 - Country Name:
 - LatLng:'
 - });
 - google.maps.event.addListener(marker, 'click', function() {
 - // 打開窗口
 - infowindow.open(map, marker);
 - });
 
將它們結(jié)合起來的代碼如下:
- 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;
 
利用上面的代碼,我們將會(huì)在頁面上創(chuàng)建一張地圖,然后定位用戶所在的區(qū)域,在這個(gè)區(qū)域加上標(biāo)記,并且彈出一個(gè)顯示位置信息的窗口。

Multiple Makers(多標(biāo)記)
有些時(shí)候,我們可以要在地圖上處理多個(gè)標(biāo)記,那么我們就可以用下面代碼來實(shí)現(xiàn):
- 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);
 - }
 - }
 

路線說明
一個(gè)最有用的特性之一是Google Maps API可以為任何指定的位置提供詳細(xì)的路線說明,實(shí)現(xiàn)代碼如下:
- 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為你提供了多層的選項(xiàng),其中有一個(gè)是自行車層。通過自行車層,可以為一些特別的位置顯示自行車路線。下面的代碼是讓你在地圖上添加自行車層:
- 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
到目前為止,我們已經(jīng)學(xué)習(xí)創(chuàng)建Google地圖的基本思想,同時(shí)也學(xué)習(xí)了如何顯示位置相關(guān)的信息。下面我們來看看用戶是如何來計(jì)算位置的,Geocoding可以計(jì)算出指定區(qū)域的經(jīng)度和緯度,下面的代碼就告訴你如何利用API計(jì)算某個(gè)位置的經(jīng)度和緯度的:
- 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#代碼來計(jì)算位置:
- 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
顧名思義,這個(gè)是Geocoding的反操作,我們可以根據(jù)經(jīng)度和緯度來找出該位置的名稱。代碼如下:
- 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#也可以實(shí)現(xiàn)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
 
總結(jié)
在這篇文章,我嘗試將V3版本的Google Maps API中的最基本和最常用的功能解說清楚。希望這篇文章能幫你順利完成任務(wù)。然后,API中還有很多我沒有討論到的,我將嘗試在今后的文章中來討論。當(dāng)然希望能得到大家的點(diǎn)評(píng)和反饋。
源碼下載:http://files.cnblogs.com/sxwgf/GMAP.zip
原文:http://www.cnblogs.com/jz1108/archive/2011/10/21/2220574.html
【編輯推薦】















 
 
 
 
 
 
 