地址之间的距离

use*_*860 8 c# google-maps

有没有办法让谷歌地图计算出2个地址之间的距离?怎么样?

saj*_*aha 17

如果你只有两个地址,首先尝试通过GEOCODING获得lat lan ,然后有很多方法来获得它们之间的距离.

要么

如果你不需要地理编码并想要一个CS解决方案试试这个:

public int getDistance(string origin, string destination)
{
    System.Threading.Thread.Sleep(1000);
    int distance = 0;
    //string from = origin.Text;
    //string to = destination.Text;
    string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
    string requesturl = url;
    //string requesturl = @"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false";
    string content = fileGetContents(requesturl);
    JObject o = JObject.Parse(content);
    try
    {
        distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
        return distance;
    }
    catch
    {
        return distance;
    }
    return distance;
    //ResultingDistance.Text = distance;
}

    protected string fileGetContents(string fileName)
    {
        string sContents = string.Empty;
        string me = string.Empty;
        try
        {
            if (fileName.ToLower().IndexOf("http:") > -1)
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                byte[] response = wc.DownloadData(fileName);
                sContents = System.Text.Encoding.ASCII.GetString(response);

            }
            else
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
                sContents = sr.ReadToEnd();
                sr.Close();
            }
        }
        catch { sContents = "unable to connect to server "; }
        return sContents;
    }
Run Code Online (Sandbox Code Playgroud)

要么

如果你不想搞乱谷歌并且只需要AIR DISTANCE,试试这个:

public decimal calcDistance(decimal latA, decimal longA, decimal latB, decimal longB)
{

    double theDistance = (Math.Sin(DegreesToRadians(latA)) *
            Math.Sin(DegreesToRadians(latB)) +
            Math.Cos(DegreesToRadians(latA)) *
            Math.Cos(DegreesToRadians(latB)) *
            Math.Cos(DegreesToRadians(longA - longB)));

    return Convert.ToDecimal((RadiansToDegrees(Math.Acos(theDistance)))) * 69.09M * 1.6093M;
}
Run Code Online (Sandbox Code Playgroud)

注意:自2018年6月11日起,由于Google已停用对Maps API的无密钥访问权限,此方法将无法运行.如果您希望使用此方法,则必须注册其云平台并启用结算功能.


Dr.*_*lle 0

向距离矩阵服务方向服务发送请求(当您需要路线距离时)