首页 > 解决方案 > Xamarin 和谷歌地图上的不同距离

问题描述

我在谷歌地图上得到不同的距离,当我在 Xamarin 中使用 CalculateDistance() 方法进行计算时。如何计算 Xamarin 中的行驶距离?有什么方法可以用来计算 c#/Xamarin 中的地图距离吗?

下面的代码计算两个位置之间的距离。但这与谷歌地图上的行驶距离不同。

var location = new Location(21.705723, 72.998199);
var otherLocation = new Location(22.3142, 73.1752);
double distance =  location.CalculateDistance(otherLocation,DistanceUnits.Kilometers);

标签: c#google-mapsxamarin.forms

解决方案


您永远无法获得谷歌地图中显示的相同距离,因为谷歌地图没有显示最短距离,但它会看到许多其他的东西,这将使汽车的距离与骑自行车或步行的距离不同。另外,今天的距离可能与昨天有所不同,因为一些道路被关闭进行维修等。

所以,实现谷歌地图智能距离计算的唯一方法就是使用自己的API

1. 自己创建对 Google Maps API 的请求

您可以将 HTTP-Requests 发送到 google maps API,然后使用结果。您可以使用WebRequest伪造对 google api 的请求。为此,您需要一个 Maps API 密钥


查看列出所有请求参数和示例响应的Google Maps Api 文档(在 Web 服务 API 下)。

C# 示例

protected void Page_Load(object sender, EventArgs e)
{
    string origin = "Oberoi Mall, Goregaon";
    string destination = "Infinity IT Park, Malad East";
    string url = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=" +
 origin + "&destinations=" + destination + "&key=CKzaDyBE188Pm_TZXCC_x5Gt67FU5vC9mEPw1";
        WebRequest request = WebRequest.Create(url);
        using (WebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (StreamReader reader = new 
            StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                DataSet dsResult = new DataSet();
                dsResult.ReadXml(reader);
                duration.Text = dsResult.Tables["duration"].Rows[0]["text"].ToString();
                distance.Text = dsResult.Tables["distance"].Rows[0]["text"].ToString();
            }
        }
    }

推荐阅读