我正在尝试在Google Maps上映射公司的所有办公室,并且在调用API时遇到了一个奇怪的问题。该代码将在大约一半的办公室地址上返回NO_RESULTS,但是当我复制使用的确切呼叫时,它将在我的浏览器中返回结果。添加 component = country:US 可以解决大多数问题,但是仍然有很多确切的问题。
这是一个例子:
1110 PELICAN BAY DRIVE代托纳海滩FL 321191381
1110%20PELICAN%20BAY%20DRIVE%20%20DAYTONA%20BEACH%20FL%20321191381
零结果
它可以在我尝试使用的任何浏览器中使用,但是当我的REST客户端调用它时则不起作用。下面的代码:
public Geolocation Locate(string address)
{
var client = new RestClient();
client.BaseUrl = new Uri("https://maps.googleapis.com/");
var request = new RestRequest("maps/api/geocode/json?components=country:US&address={address}&key=KEY");
request.AddParameter("address", Uri.EscapeDataString(address), ParameterType.UrlSegment);
var response = client.Execute<Geolocation>(request);
return response.Data;
}
以上是我调用API的服务,下面是实现方法。
officeObj.Address = office.ADDR1.Trim() + " " +
office.ADDR2.Trim() + " " +
office.CITY.Trim() + " " +
office.STATE.Trim() + " " +
office.ZIP.Trim();
Geolocation geolocation = _geolocationService.Locate(officeObj.Address);
var location = geolocation?.results.FirstOrDefault()?.geometry?.location;
答案 0 :(得分:0)
事实证明,问题完全归因于RestSharp。替换为沼泽标准HttpClient可以解决整个问题,因此它似乎是该库中的错误。
答案 1 :(得分:0)
您需要正确使用RestSharp。这段代码可以很好地工作。
public static IRestResponse Locate(string address)
{
var client = new RestClient();
client.BaseUrl = new Uri("https://maps.googleapis.com/");
client.AddDefaultParameter("key", ApiKey, ParameterType.QueryString);
var request = new RestRequest("maps/api/geocode/json?components=country:US");
request.AddQueryParameter("address", address);
return client.Get(request);
}