ASP.NET中使用Google Maps API V3【译】

写在最前面

早就听说过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服务的:

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

然后你可以用下面的代码来创建一个简单的地图:

1
2
3
4
5
6
7
8
9
10
11
function InitializeMap()
{
    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"), myOptions);
}
window.onload = InitializeMap;

 

Google Maps 设置选项

在上面的例子中,我们使用了一个Map类,并设置了一个HTML ID作为参数。现在我们来更深入一点,一起来看看下面的地图选项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var options =
    {
        zoom: 3,
        center: new google.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: true,
        draggable: false,
        streetViewControl: true,
        draggableCursor: 'move'
    };
    var map = new google.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类提供了这样一个选项,为用户指定的位置显示一个标记,在我们的应用中地图标记是十分常用的,下面的代码将告诉大家如何创建一个简单的地图标记:

1
2
3
4
5
6
7
8
var marker = new google.maps.Marker
(
    {
        position: new google.maps.LatLng(-34.397, 150.644),
        map: map,
        title: 'Click me'
    }
);

 

Info Window(信息窗口)

我们已经在地图上某个位置加了标记,也为标记添加onclick了事件,点击可以弹出一个窗口来显示该地点的详细信息。我们可以按照下面的代码来创建信息窗口:

1
2
3
4
5
6
7
8
9
var infowindow = new google.maps.InfoWindow({
    content: 'Location info:
    Country Name:
    LatLng:'
});
google.maps.event.addListener(marker, 'click', function () {
    // 打开窗口
    infowindow.open(map, marker);
});

将它们结合起来的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var map;
function initialize() {
    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"), myOptions);
    var marker = new google.maps.Marker
    (
        {
            position: new google.maps.LatLng(-34.397, 150.644),
            map: map,
            title: 'Click me'
        }
    );
    var infowindow = new google.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(多标记)

有些时候,我们可以要在地图上处理多个标记,那么我们就可以用下面代码来实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function markicons() {
    InitializeMap();
    var ltlng = [];
 
    ltlng.push(new google.maps.LatLng(40.756, -73.986));
    ltlng.push(new google.maps.LatLng(37.775, -122.419));
    ltlng.push(new google.maps.LatLng(47.620, -122.347));
    ltlng.push(new google.maps.LatLng(-22.933, -43.184));
 
 
    for (var i = 0; i <= ltlng.length; i++) {
        marker = new google.maps.Marker({
            map: map,
            position: ltlng[i]
        });
 
        (function (i, marker) {
 
            google.maps.event.addListener(marker, 'click', function () {
 
                if (!infowindow) {
                    infowindow = new google.maps.InfoWindow();
                }
 
                infowindow.setContent("Message" + i);
 
                infowindow.open(map, marker);
 
            });
 
        })(i, marker);
    }
}

 

路线说明

一个最有用的特性之一是Google Maps API可以为任何指定的位置提供详细的路线说明,实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
 
function InitializeMap() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    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"), myOptions);
 
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directionpanel'));
 
    var control = document.getElementById('control');
    control.style.display = 'block';
 
 
}
    function calcRoute() {
 
    var start = document.getElementById('startvalue').value;
    var end = document.getElementById('endvalue').value;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
 
}
 
function Button1_onclick() {
    calcRoute();
}
 
window.onload = InitializeMap;

 

Layers

Google Maps API为你提供了多层的选项,其中有一个是自行车层。通过自行车层,可以为一些特别的位置显示自行车路线。下面的代码是让你在地图上添加自行车层:

1
2
3
4
5
6
7
8
9
10
11
12
13
var map
function InitializeMap() {
    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"), myOptions);
}
window.onload = InitializeMap;
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);

Geocoding

 

到目前为止,我们已经学习创建Google地图的基本思想,同时也学习了如何显示位置相关的信息。下面我们来看看用户是如何来计算位置的,Geocoding可以计算出指定区域的经度和纬度,下面的代码就告诉你如何利用API计算某个位置的经度和纬度的:

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
    }
});

Geocoding C#

 

同样我们可以利用C#代码来计算位置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static Coordinate GetCoordinates(string region)
{
    using (var client = new WebClient())
    {
 
        string uri = "http://maps.google.com/maps/geo?q='" + region +
          "'&output=csv&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1" +
          "-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA";
 
        string[] geocodeInfo = client.DownloadString(uri).Split(',');
 
        return new Coordinate(Convert.ToDouble(geocodeInfo[2]),
                   Convert.ToDouble(geocodeInfo[3]));
    }
}
 
public struct Coordinate
{
    private double lat;
    private double lng;
 
    public Coordinate(double latitude, double longitude)
    {
        lat = latitude;
        lng = longitude;
 
    }
 
    public double Latitude { get { return lat; } set { lat = value; } }
    public double Longitude { get { return lng; } set { lng = value; } }
 
}

Reverse Geocoding

 

顾名思义,这个是Geocoding的反操作,我们可以根据经度和纬度来找出该位置的名称。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var map;
var geocoder;
function InitializeMap() {
 
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions =
    {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
}
 
function FindLocaiton() {
    geocoder = new google.maps.Geocoder();
    InitializeMap();
 
    var address = document.getElementById("addressinput").value;
    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
            });
            if (results[0].formatted_address) {
                region = results[0].formatted_address + '
';
            }
            var infowindow = new google.maps.InfoWindow({
                content: 'Location info:
Country Name:' + region +
                '
LatLng:' + results[0].geometry.location + ''
            });
            google.maps.event.addListener(marker, 'click', function () {
                // Calling the open method of the infoWindow
                infowindow.open(map, marker);
            });
 
        }
        else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

Reverse Geocoding in C#

 

同样用C#也可以实现Reverse Geocoding操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
static string baseUri =
string location = string.Empty;
 
 
public static void RetrieveFormatedAddress(string lat, string lng)
{
    string requestUri = string.Format(baseUri, lat, lng);
 
    using (WebClient wc = new WebClient())
    {
        string result = wc.DownloadString(requestUri);
        var xmlElm = XElement.Parse(result);
        var status = (from elm in xmlElm.Descendants() where
            elm.Name == "status" select elm).FirstOrDefault();
        if (status.Value.ToLower() == "ok")
        {
            var res = (from elm in xmlElm.Descendants() where
                elm.Name == "formatted_address" select elm).FirstOrDefault();
            requestUri = res.Value;
        }
    }
}

总结

 

在这篇文章,我尝试将V3版本的Google Maps API中的最基本和最常用的功能解说清楚。希望这篇文章能帮你顺利完成任务。然后,API中还有很多我没有讨论到的,我将尝试在今后的文章中来讨论。当然希望能得到大家的点评和反馈。

示例源码下载

posted @ 2013-03-13 11:38  程序新青年  阅读(263)  评论(0编辑  收藏  举报
============================================================================== 青春匆匆,很多人都有自己的座右铭,鞭策自己前进,当没看到座右铭的时候又忘了自己要干什么,就这样天天立志,志天天立,最终还是那个初出茅庐的小菜鸟。从现在开始,慢慢去改掉懒惰的习惯。慢慢去加强学习,直到慢慢成功。==============================================================================