我正在使用 C# 开发移动 android 应用程序,我需要在其中显示路线并计算它的距离。
最佳答案
要显示一条路线,您首先需要计算它。您可以使用 google Direction API 来做到这一点。很酷的是,它还会为您返回总距离。因此,只需一个请求即可满足您的所有要求。
Google Directions API 有很多请求示例,您可以通过名称引用它们来计算两地之间的道路。但最直接的是使用纬度和经度。例如:
https://maps.googleapis.com/maps/api/directions/json?origin=lat1,lon1&destination=lat2,lon2&key=yourApiKey
您可以从 Google 控制台获取 API key 。
您可以播放并更改此链接中的变量并在浏览器中打开它,以查看返回的对象。
当您收到返回对象时,您需要对其进行解析。
距离将在 googleApiRouteObject.routes[0].legs[0].distance;
您会在 meeters 中找到一个 int 表示,以及像 2.3km 这样的字符串表示。
航路点将在折线中编码,您需要对它们进行解析。您可以在此处找到如何使用代码示例执行此操作:https://developers.google.com/maps/documentation/utilities/polylineutility
有一个例子:
List<Android.Locations.Location> FnDecodePolylinePoints(string encodedPoints)
{
if ( string.IsNullOrEmpty ( encodedPoints ) )
return null;
var poly = new List<Android.Locations.Location>();
char[] polylinechars = encodedPoints.ToCharArray();
int index = 0;
int currentLat = 0;
int currentLng = 0;
int next5bits;
int sum;
int shifter;
try
{
while (index < polylinechars.Length)
{
// calculate next latitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polylinechars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polylinechars.Length);
if (index >= polylinechars.Length)
break;
currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
//calculate next longitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polylinechars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polylinechars.Length);
if (index >= polylinechars.Length && next5bits >= 32)
break;
currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
Android.Locations.Location p = new Android.Locations.Location("");
p.Latitude = Convert.ToDouble(currentLat) / 100000.0;
p.Longitude = Convert.ToDouble(currentLng) / 100000.0;
poly.Add(p);
}
}
catch
{
}
return poly;
}
现在,您需要将它们绘制在 map 上。我建议您为此使用谷歌地图。
// Decode the points
var lstDecodedPoints = FnDecodePolylinePoints(encodedPoints);
//convert list of location point to array of latlng type
var latLngPoints = new LatLng[lstDecodedPoints.Count];
int index = 0;
foreach (Android.Locations.Location loc in lstDecodedPoints){
latLngPoints[index++] = new LatLng(loc.Latitude, loc.Longitude);}
// Create polyline
var polylineoption = new PolylineOptions();
polylineoption.InvokeColor(Android.Graphics.Color.GRREN);
polylineoption.Geodesic(true);
polylineoption.Add(latLngPoints);
// Don't forget to add it to the main quie, if you was doing the request for a cordinate in background
// Add polyline to map
this.Activity.RunOnUiThread(() =>
_map.AddPolyline(polylineoption));
}
基本上就是这样,您将获得与 img 上非常接近的结果。
关于c# - Xamarin android Google Maps API 计算和显示路线并计算路线距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47187694/