对于这种特殊情况,如何使用地理编码获得公司的正确位置? (Python, Google API)

How can I get the proper location of a company using geocode for this particular case? (Python, Google API)

我想获得已清理的数据框中列出的公司的经纬度,但我拥有的唯一信息是公司名称和国家/地区(在本例中为英国)。

DataFrame

在尝试了不同的东西之后,我得到了一些经纬度,但在大多数情况下,我没有得到位于英国的经纬度。 这是我试过的代码:

base_url= "https://maps.googleapis.com/maps/api/geocode/json?"
AUTH_KEY = "AI**************QTk"
geolocator = GoogleV3(api_key = AUTH_KEY)

parameters = {"address": "Revolut, London",
             "key": AUTH_KEY}
print(f"{base_url}{urllib.parse.urlencode(parameters)}")
r = requests.get(f"{base_url}{urllib.parse.urlencode(parameters)}")
data = json.loads(r.content)
data.get("results")[0].get("geometry").get("location")   #That works for the first company

df["loc"] = df["Company name for communication"].apply(geolocator.geocode)
df["point"]= df["loc"].apply(lambda loc: tuple(loc.point) if loc else None)
df[['lat', 'lon', 'altitude']] = pd.DataFrame(df['point'].to_list(), index=df.index)

DataFrame with long and lat wrong

我非常同意任何帮助。如果我的解释不清楚以提供更多详细信息,请告诉我。谢谢!

如果您只想在英国获得地理编码 API 结果,那么您可能需要使用组件过滤。

地理编码 API 可以 return 解决限制在特定区域的结果。您可以使用 components 过滤器指定限制。有关详细信息,请参阅 Component Filtering。具体来说,您可能希望包括 country.

请注意,该值应该是国家名称或两个字母 ISO 3166-1 国家代码。 API 遵循 ISO 定义国家的标准,使用国家对应的 ISO 代码过滤效果最佳。例如

这是一个在英国进行国家/地区组件过滤的示例地理编码 Web 请求,如下所示:

https://maps.googleapis.com/maps/api/geocode/json?address=high+st+hasting&components=country:gb&key=YOUR_API_KEY

这只会 return 一个仅位于英国的结果,如果不可用,将 return 零个结果。

您可能还想看看 region biasing

Note that if you bias for the region, the returned result prefers results in the country, but doesn't restrict them to that country and will return a result for an address. Unlike component filtering, this takes a ccTLD (country code top-level domain) argument specifying the region bias. Most ccTLD codes are identical to ISO 3166-1 codes, with some notable exceptions. For example, the United Kingdom's ccTLD is "uk" (.co.uk) while its ISO 3166-1 code is "gb" (technically for the entity of "The United Kingdom of Great Britain and Northern Ireland").

也请看看Geocoding API Best Practices

我用这段代码使用组件过滤得到了结果:

#Get the location of first company
base_url= "https://maps.googleapis.com/maps/api/geocode/json?"
AUTH_KEY = "AI********************Tk"
geolocator = GoogleV3(api_key = AUTH_KEY)

components = [ ('country', 'GB' )]
def get_location(x):
    return geolocator.geocode(x, components=components)

df["loc"] = df["Company name for communication"].apply(get_location)
df["point"]= df["loc"].apply(lambda loc: tuple(loc.point) if loc else None)
df[['lat', 'lon', 'altitude']] = pd.DataFrame(df['point'].to_list(), index=df.index)
df

DataFrame with lat and lon