为什么Google距离矩阵API传递52时仅返回10个结果?

时间:2019-05-22 22:05:32

标签: c# google-api restsharp google-distancematrix-api

我正在尝试从源地址获取各种地址的距离,并且能够调用Google距离矩阵API,但是仅返回10个结果,而不是每个发送地址的结果。我在C#中使用restsharp库。 我从文档中了解到,该文档一次最多可以处理100个地址。

private void CalculateDistance(List<StoreViewModel> tempList, string lattitude, string longitude)
    {
        var url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&key=removedForStackOverflowPostInsertYourKeyHere&origins=";
        string destinations = string.Empty;
        foreach(StoreViewModel vm in tempList)
        {
            destinations += "|";
            destinations += vm.AddressLine1;
            destinations += string.IsNullOrWhiteSpace(vm.AddressLine2) ? "" : "+" + vm.AddressLine2;
            destinations += string.IsNullOrWhiteSpace(vm.AddressLine3) ? "" : "+" + vm.AddressLine3;
            destinations += "+" + vm.City;
            destinations += "+" + vm.State;
            destinations += "+" + vm.ZIP;
            destinations += "|";
        }
        url += lattitude + "," + longitude;
        url += "&destinations=";
        url += destinations;
        var client = new RestClient(url);
        var request = new RestRequest(Method.GET);
        request.RequestFormat = DataFormat.Json;
        request.AddHeader("Content-Type", "application/json; charset=utf-8");
        var response = client.Execute(request);
        var jsonObject = System.Web.Helpers.Json.Decode(response.Content);
        int i = 0;
        foreach(var row in jsonObject.rows)
        {
            foreach(var element in row.elements)
            {
                if(element!=null && element.distance!=null)
                {
                    tempList[i].DistanceFromUser = element.distance.value;
                    tempList[i].DistanceFromUserText = element.distance.text;
                }
                else
                {
                    tempList[i].DistanceFromUser = 99999999;
                    tempList[i].DistanceFromUserText = "Distance not available.";
                }
                i++;
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

答案是这种类型的方法创建的查询字符串太长,以至于请求中只有这么多个地址。因此Google API工作正常,但是我的请求被最大查询长度截断了。我通过使用提琴手并检查请求值发现它,发现其中只有10个地址。