How can I forward the client's IP Address to Google Places Autocomplete API

Viewed 981

I am calling Google Places Autocomplete API from a web server, so when the client code is unable to capture latitude/longitude from the browser, location biasing will always be based on my server's IP address by default. I am trying to find a way to pass to Google the client's IP address instead of it using mine. I have captured the client IP on my server API, but there doesn't seem to be any way to forward that in an Autocomplete request.

From the documentation, Google states:

Note: If you do not supply the location and radius, the API will attempt to detect the user's location from their IP address, and will bias the results to that location.

I've attempted to add different headers to the Autocomplete Request, but they are all ignored and still bias results on my server IP. Maybe I haven't found the correct header.

//pseudo C#
headers.Add("X-ProxyUser-Ip", "172.217.5.228");
headers.Add("X-Forwarded-For", "172.217.5.228");

Is there a proper way to forward a client IP from my server to Google API?

src: https://developers.google.com/places/web-service/autocomplete#location_biasing

2 Answers

Currently, Google Places server-side API does not support IP address as a parameter for location biasing. So you have two options.

  1. Use client-side API (You have mentioned this is not feasible)
  2. Call a reverse geolocation API to get the country code of an IP. Then pass this country code to Google places API via components parameter.

example for Ipfind service

using (var webClient = new System.Net.WebClient()) {
  string ip_address = "10.23.45.154";
  string URL = "https://api.ipfind.com/?ip=" + ip_address;

  var json = webClient.DownloadString(URL);
  // extract ISO country code here and call Google Places API
}

components — A grouping of places to which you would like to restrict your results. Currently, you can use components to filter by up to 5 countries. Countries must be passed as a two character, ISO 3166-1 Alpha-2 compatible country code. For example: components=country:fr would restrict your results to places within France. Multiple countries must be passed as multiple country:XX filters, with the pipe character (|) as a separator. For example: components=country:us|country:pr|country:vi|country:gu|country:mp would restrict your results to places within the United States and its unincorporated organized territories.

I will assume you've already looked through official Google documentation and restricting a key to your owned domain does not suit you.

I guess then you can try calling a 3rd party API to roughly bias client IP to location and the use it for you Google autocomplete.

Related