Wolvenhaven
Wolvenhaven

Reputation: 335

Google Maps Geocode API returns NO_RESULTS programatically but returns results in the browser with the same URL

I am trying to map all of my company's offices on Google Maps and I'm running into a strange issue when calling the API. The code will return a NO_RESULTS on about half the office addresses, but when I copy the exact call used, it will return results in my browser. Adding component=country:US solved most of them but there are still quite a few with this exact issue.

This is an example of one:

https://maps.googleapis.com/maps/api/geocode/json?components=country:US&address=1110%20PELICAN%20BAY%20DRIVE%20%20DAYTONA%20BEACH%20FL%20321191381&key=KEY

1110 PELICAN BAY DRIVE DAYTONA BEACH FL 321191381

1110%20PELICAN%20BAY%20DRIVE%20%20DAYTONA%20BEACH%20FL%20321191381

ZERO_RESULTS

It works in any browser I try it in, but doesn't work when called by my REST client. Code below:

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;
    }

Above is my service to call the API, and here is how it is implemented.

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;

Upvotes: 1

Views: 549

Answers (2)

Alexey Zimarev
Alexey Zimarev

Reputation: 19610

You need to use RestSharp correctly. This code works perfectly fine.

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);
}

Upvotes: 1

Wolvenhaven
Wolvenhaven

Reputation: 335

Turns out the issue is entirely due to RestSharp. Replacing it with a bog standard HttpClient solved the entire issue, so it appear to be a bug in that library.

Upvotes: 0

Related Questions