使用C#/XAML Metro应用中的Bing地图绘制路线

在Windows 8应用中,经常需要实现从一个地点到另一个地点的路线绘制功能。本文将介绍如何使用Bing地图REST服务来实现这一功能。首先,需要了解Bing地图的REST服务以及如何使用C#/XAML来调用这些服务。

在实现之前,需要确保已经安装了Bing地图SDK,并且拥有使用这些服务的密钥。可以通过CodeProject的文章了解Bing地图的基本操作,然后添加Bing地图REST服务.NET库。需要注意的是,Bing地图在某些地区可能不受支持,可以通过特定链接检查支持情况。如果不支持,地图上将显示一个带有红色叉号的圆圈。为了设置支持的区域,需要设置HomeRegion属性,否则它将使用Windows 8用户的区域。

接下来,将创建一个线程来异步获取响应。线程将获取REST服务的URL,该URL可以包含两个位置的坐标或地标作为参数,并返回一个JSON字符串。将使用DataContractJsonSerializer类来序列化JSON响应。

private async Task GetResponse(Uri uri) { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); var response = await client.GetAsync(uri); using (var stream = await response.Content.ReadAsStreamAsync()) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response)); return ser.ReadObject(stream) as Response; } } private async void btnGiveDirections_Click(object sender, RoutedEventArgs e) { try { tbError.Text = string.Empty; if (rdCoord.IsChecked == true) { URL = "http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0=" + txtFromCoord.Text + "&wp.1=" + txtToCoord.Text + "&optmz=distance&rpo=Points&key=" + MyMap.Credentials; } else { URL = "http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0=" + txtFromLocation.Text + "&wp.1=" + txtToLocation.Text + "&optmz=distance&rpo=Points&key=" + MyMap.Credentials; } Uri geocodeRequest = new Uri(URL); BingMapsRESTService.Response r = await GetResponse(geocodeRequest); geolocator = new Geolocator(); MyPushPin = new Pushpin(); FromLatitude = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[0][0]; FromLongitude = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[0][1]; location = new Location(FromLatitude, FromLongitude); MapLayer.SetPosition(MyPushPin, location); MyMap.Children.Add(MyPushPin); MyMap.SetView(location, 15.0f); MapPolyline routeLine = new MapPolyline(); routeLine.Locations = new LocationCollection(); routeLine.Color = Windows.UI.Colors.Blue; routeLine.Width = 5.0; int bound = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates.GetUpperBound(0); for (int i = 0; i < bound; i++) { routeLine.Locations.Add(new Location { Latitude = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[i][0], Longitude = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[i][1] }); } MapShapeLayer shapeLayer = new MapShapeLayer(); shapeLayer.Shapes.Add(routeLine); MyMap.ShapeLayers.Add(shapeLayer); } catch (Exception) { tbError.Text = "Error Occured !!! Please Try Again"; } }
沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485