get_place_id.py
· 1.1 KiB · Python
Raw
import requests
def get_place_id(api_key, query):
# Google Places API endpoint
endpoint = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json"
# Parameters
params = {
"input": query, # Input can be the name or address
"inputtype": "textquery",
"fields": "place_id", # Request only the `place_id` field
"key": api_key
}
# API Call
response = requests.get(endpoint, params=params)
# Check if the request was successful
if response.status_code == 200:
data = response.json()
if "candidates" in data and len(data["candidates"]) > 0:
return data["candidates"][0]["place_id"] # Return the first candidate's place_id
else:
return f"No results found for query: {query}"
else:
return f"Error: {response.status_code} - {response.text}"
# Example usage
if __name__ == "__main__":
# Replace with your API key
YOUR_API_KEY = "your_google_api_key"
QUERY = "Le Bernardin, New York, NY"
place_id = get_place_id(YOUR_API_KEY, QUERY)
print(f"Place ID: {place_id}")
1 | import requests |
2 | |
3 | def get_place_id(api_key, query): |
4 | # Google Places API endpoint |
5 | endpoint = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json" |
6 | |
7 | # Parameters |
8 | params = { |
9 | "input": query, # Input can be the name or address |
10 | "inputtype": "textquery", |
11 | "fields": "place_id", # Request only the `place_id` field |
12 | "key": api_key |
13 | } |
14 | |
15 | # API Call |
16 | response = requests.get(endpoint, params=params) |
17 | |
18 | # Check if the request was successful |
19 | if response.status_code == 200: |
20 | data = response.json() |
21 | if "candidates" in data and len(data["candidates"]) > 0: |
22 | return data["candidates"][0]["place_id"] # Return the first candidate's place_id |
23 | else: |
24 | return f"No results found for query: {query}" |
25 | else: |
26 | return f"Error: {response.status_code} - {response.text}" |
27 | |
28 | # Example usage |
29 | if __name__ == "__main__": |
30 | # Replace with your API key |
31 | YOUR_API_KEY = "your_google_api_key" |
32 | QUERY = "Le Bernardin, New York, NY" |
33 | place_id = get_place_id(YOUR_API_KEY, QUERY) |
34 | print(f"Place ID: {place_id}") |