Get a business' name with Google Maps API - python

Inverse to most location querying efforts, I am actually trying to identify a business' name with Google APIs by either its address or Google placeid. e.g., when I search for 1625 Wilshire Blvd, Los Angeles, CA 90017 on googlemaps.com, its results show me that "at this location" is "McDonald's".
However, when making the API call with the following URL, the name comes up as the street address, when what I want is to identify the business' name at that location ("McDonald's"):
https://maps.googleapis.com/maps/api/place/textsearch/json?query=1625%20Wilshire%20Blvd,%20Los%20Angeles,%20CA%2090017&sensor=false&key=<api_key>
EDIT: Using the exact call that #xomena recommended, I'm still having the same issue. I've run it both R and Python and the result I’m getting is the street address in place of the name with both ways.
R Code:
packages <- c("RJSONIO")
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)
library(RJSONIO)
fromJSON(URLencode(paste("https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=1625%20Wilshire%20Blvd%2C%20Los%20Angeles%2C%20CA%2090017&inputtype=textquery&fields=formatted_address,name,place_id&key=", api_key, sep = "")))
R Output:
$candidates
$candidates[[1]]
formatted_address
"1625 Wilshire Blvd, Los Angeles, CA 90017, USA"
name
"1625 Wilshire Blvd"
place_id
"ChIJ18AW_aPHwoARXRm-cgcRcDs"
$debug_log
$debug_log$line
list()
$status
[1] "OK"
Python Code:
import requests
requests.get("https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=1625%20Wilshire%20Blvd%2C%20Los%20Angeles%2C%20CA%2090017&inputtype=textquery&fields=formatted_address,name,place_id&key="+API_KEY).json()
Python Output:
{'candidates': [{'formatted_address': '1625 Wilshire Blvd, Los Angeles, CA 90017, USA',
'name': '1625 Wilshire Blvd',
'place_id': 'ChIJ18AW_aPHwoARXRm-cgcRcDs'}],
'debug_log': {'line': []},
'status': 'OK'}

Maybe you can get business name by using Google Place Autocomplete requests:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=601%20East%20Kennedy%20Blvd,%20Tampa,%20FL,%20USA&types=establishment&language=en&key=YOUR_API_KEY
I get the following response:
{"predictions":[
{
"description" : "Quest Diagnostics Inside New Castle Walmart Store, 117 Wilton Blvd, New Castle, DE 19720, USA",
"id" : "8295289e301fd05ae69a8d3cd8d25da31c29c66d",
"matched_substrings" : [
{
"length" : 10,
"offset" : 25
},
{
"length" : 11,
"offset" : 55
},
{
"length" : 2,
"offset" : 80
},
{
"length" : 5,
"offset" : 83
},
{
"length" : 3,
"offset" : 90
}
],
"place_id" : "ChIJtTv6_PsHx4kRYZZtvcrallQ",
"reference" : "ChIJtTv6_PsHx4kRYZZtvcrallQ",
"structured_formatting" : {
"main_text" : "Quest Diagnostics Inside New Castle Walmart Store",
"main_text_matched_substrings" : [
{
"length" : 10,
"offset" : 25
}
],
"secondary_text" : "117 Wilton Blvd, New Castle, DE 19720, USA",
"secondary_text_matched_substrings" : [
{
"length" : 11,
"offset" : 4
},
{
"length" : 2,
"offset" : 29
},
{
"length" : 5,
"offset" : 32
},
{
"length" : 3,
"offset" : 39
}
]
},
"terms" : [
{
"offset" : 0,
"value" : "Quest Diagnostics Inside New Castle Walmart Store"
},
{
"offset" : 51,
"value" : "117 Wilton Blvd"
},
{
"offset" : 68,
"value" : "New Castle"
},
{
"offset" : 80,
"value" : "DE"
},
{
"offset" : 83,
"value" : "19720"
},
{
"offset" : 90,
"value" : "USA"
}
],
"types" : [ "health", "point_of_interest", "establishment" ]
}],"status" : "OK"}
I think predictions[0].description has business name.
But not every time the response is returned. The response's predictions may be an empty array.

I believe the Find place endpoind is doing what you are looking for
When I execute the following request
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=1625%20Wilshire%20Blvd%2C%20Los%20Angeles%2C%20CA%2090017&inputtype=textquery&fields=formatted_address,name,place_id&key=MY_API_KEY
I get the following response
{
"candidates":[
{
"formatted_address":"1625 Wilshire Blvd, Los Angeles, CA 90017, USA",
"name":"McDonald's",
"place_id":"ChIJ0QBm-6PHwoARpfbcollvKIc"
}
],
"debug_log":{
"line":[
]
},
"status":"OK"
}
As you can see the Find place returns McDonald's business.
I hope this helps!
Update
Interesting. Do you know by chance where is located your server? As you can see in the documentation, by default find place uses IP address bias. My server is located in the US and I get McDonald's, if your server IP address is from different area you can get a different results due to location biasing. In this case I can suggest specifying an area to bias your results, for example define circle or rectangle area. The request should be similar to
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=1625%20Wilshire%20Blvd%2C%20Los%20Angeles%2C%20CA%2090017&inputtype=textquery&fields=formatted_address,geometry,name,place_id&locationbias=circle%3A100%4034.0559572%2C-118.2708558&key=YOUR_API_KEY

Related

How to get a high-quality image from an IIIFv21 API in Python?

I have an info.json file in the IIIFv21 format, and I want to use it to retrieve high-quality image tiles. We can use, for example, the file that is available here and looked like:
> {
"#context" : "http://iiif.io/api/image/2/context.json",
"#id" : "https://iiif.nli.org.il/IIIFv21/FL202979482",
"protocol" : "http://iiif.io/api/image",
"width" : 5414,
"height" : 3763,
"sizes" : [ {
"width" : 84,
"height" : 58
}, {
"width" : 169,
"height" : 117
}, {
"width" : 338,
"height" : 235
}, {
"width" : 676,
"height" : 470
}, {
"width" : 1353,
"height" : 940
}, {
"width" : 2707,
"height" : 1881
} ],
"tiles" : [ {
"width" : 1024,
"height" : 1024,
"scaleFactors" : [ 1, 2, 4, 8, 16, 32, 64 ]
} ],
"profile" : [ "http://iiif.io/api/image/2/level1.json", {
"formats" : [ "jpg" ],
"qualities" : [ "native", "color", "gray", "bitonal" ],
"supports" : [ "regionByPct", "regionSquare", "sizeByForcedWh", "sizeByWh", "sizeAboveFull", "rotationBy90s", "mirroring" ],
"maxWidth" : 526,
"maxHeight" : 526,
"maxArea" : 111111
} ],
"rights" : "http://web.nli.org.il/sites/NLI/Hebrew/library/items-terms-of-use/Pages/nli-copying-prohibited.aspx"
}
I have been trying to follow the IIIF specification, but I'm struggling to retrieve any tile. I've tried a few different approaches, but they haven't been successful.
Some of my attempts are:
https://iiif.nli.org.il/IIIFv21/FL202979451/0,0,1024,1024/1024,/0/default.jpg
https://iiif.nli.org.il/IIIFv21/FL202979451/0,0,1024,1024/1024,1024/0/default.jpg
https://iiif.nli.org.il/IIIFv21/FL202979451/0,0/1024,1024/0/default.jpg
https://iiif.nli.org.il/IIIFv21/FL202979451/0/0,0,1024,1024/1024,/0/default.jpg
https://iiif.nli.org.il/IIIFv21/FL202979451/0/0,0,1024,1024/1024,1024/0/default.jpg
https://iiif.nli.org.il/IIIFv21/FL202979451/0/0,0/1024,1024/0/default.jpg
You can change the values in the 1024s to match the desired tile location, but this is the top left tile.
Thank you in advance for any assistance you can provide.
When you use image ID FL58252370 in a valid URL - for example:
https://iiif.nli.org.il/IIIFv21/FL202979482/full/max/0/default.jpg
Then you get "unauthorized" as your response:
<error>
<parameter>unauthorized</parameter>
<text>
Error, no permissions, please contact administrator
</text>
</error>
You simply do not have access to that specific image.
(Or, maybe that is not a valid image ID. But the fact that you can retrieve the info.json response suggests it should be a valid image ID.)
If you replace that image ID with the ID of a valid, publicly accessible image...
FL58252370
...then the above URL will work:
https://iiif.nli.org.il/IIIFv21/FL58252370/full/max/0/default.jpg
You can take this new ID and use it in your 6 attempts to see which URLs are valid (some of them are; some others are not).
The web site provides detailed guidance here, showing how to construct a valid image URL.
If you believe you should have access to the image for FL58252370, then I guess you need to contact the NLI.

Python: How to display json results nicely?

I am currently building a Telegram Bot and getting JSON response on Google Places API to return nearby locations to users.
The json Response I get is as follows:
results" : [
{
"name" : "Golden Village Tiong Bahru",
"opening_hours" : {
"open_now" : true
},
"rating" : 4.2,
"types" : [ "movie_theater", "point_of_interest", "establishment" ],
"user_ratings_total" : 773
},
{
"name" : "Cathay Cineplex Cineleisure Orchard",
"opening_hours" : {
"open_now" : true
},
"rating" : 4.2,
"types" : [ "movie_theater", "point_of_interest", "establishment" ],
"user_ratings_total" : 574
}
]
My current code to get specific items in the dictionary
json.dumps([[s['name'], s['rating']] for s in object_json['results']], indent=3)
Current Results:
[
[
"Golden Village Tiong Bahru",
4.2
],
[
"Cathay Cineplex Cineleisure Orchard",
4.2
]
]
I would like to get the name and rating and display side by side instead:
Golden Village Tiong Bahru : 4.2,
Cathay Cineplex Cineleisure Orchard : 4.2
Please help.
Do you want json format as a result?
Then you can do:
json.dumps({
s['name']: s['rating']
for s in object_json['results']
}, indent=3)
If you want just string list:
lines = [f"{s['name']}: {s['rating']}" for s in object_json['results']]
Or you want to print only:
for s in object_json['results']:
print(f"{s['name']}: {s['rating']}")
You need 3.6 or higher python interpreter to use f-string(f"...").
I you don't, replace
f"{s['name']}: {s['rating']}" -> '{name}: {rating}'.format(**s)
Maybe with:
json.dumps([s['name'] + ": " + str(s['rating']) for s in object_json['results']], indent=3)

Add dict into Item dynamodb python

I have an item register on dynamodb with the next structure:
{
"OwnerID":"12312wqeq",
"license":"23423werwegdf",
"MaintenanceList":{
"10-11-2018":{
"garage" : "lopcars",
"city" : "NY",
"country" "USA",
"location" : "1929-1927 Fulton St Brooklyn"
}
}
}
I need to add a new Maintenance to the list, and I tried this:
response=table.update_item(
Key={
"OwnerID":"12312wqeq",
"license":"23423werwegdf",'
}
,UpdateExpression = "SET #d1=:dt",
ExpressionAttributeValues = {
':dt' : "12-11-2019":{
"garage" : "Crazycars",
"city" : "NY",
"country" "USA",
"location" : "120 E Suffolk Ave Central Islip"
}
}
},
ExpressionAttributeNames={
'#d1' : 'MaintenanceList'
},
ReturnValues="UPDATED_NEW"
)
but overwrite the attribute MaintenanceList and I need it to look like this after update:
{
"OwnerID":"12312wqeq",
"license":"23423werwegdf",
"MaintenanceList":{
"10-11-2018":{
"garage" : "lopcars",
"city" : "NY",
"country" "USA",
"location" : "1929-1927 Fulton St Brooklyn"
},
"12-11-2019":{
"garage" : "Crazycars",
"city" : "NY",
"country" "USA",
"location" : "120 E Suffolk Ave Central Islip"
}
}
}
The SET MaintenanceList=:dt expression indeed replaces the value of the the attributed called MaintenanceList. If you wanted the content of this attribute to be a hash table, and add to it, you need to update it using a nested atribute path as explained in this DynamoDB documentation. For example do something like SET #d1.#date=:dt.
However, note that keeping a hash table inside a single attribute's value is problematic - its total size is strictly limited (to 400KB) and you'll also pay for the entire item size every time you read or write a small part of it.

Geocoded_Waypoints Google Maps Api Zero Results

I am using google maps api with this python code to print a route between two points.
import requests, json
#Google MapsDdirections API endpoint
endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'AIzaSyCTPkufBttRcfSkA9zPYgivrYs9QEhdEEU'
#Asks the user to input Where they are and where they want to go.
origin = input('Where are you?: ').replace(' ','+')
destination = input('Where do you want to go?: ').replace(' ','+')
#Building the URL for the request
nav_request = 'origin={}&destination={}&key={}'.format(origin,destination,api_key)
request = endpoint + nav_request
#Sends the request and reads the response.
#response = urllib.request.urlopen(request).read()
r = requests.get('https://maps.googleapis.com/maps/api/directions/json?origin=Vigo&destination=Lugo&key=AIzaSyCTPkufBttRcfSkA9zPYgivrYs9QEhdEEU')
#Loads response as JSON
#directions = json.loads(response)
directions = r.json()
print(directions)
The problem is that my response gives me ZERO_RESULTS.
I´ve tried it manually in google chrome getting the next result:
{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "ChIJbYcwsYDOMQ0RDAVnKL9fMB8",
"types" : [ "locality", "political" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJk8GyYRRiLw0Rn9RLF60dRHs",
"types" : [ "locality", "political" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 43.0082848,
"lng" : -7.554997200000001
},
"southwest" : {
"lat" : 42.2392374,
"lng" : -8.720694999999999
}
},
"copyrights" : "Datos de mapas ©2019 Inst. Geogr. Nacional",
"legs" : [
{
"distance" : {
"text" : "188 km",
"value" : 188311
},
"duration" : {
"text" : "2h 11 min",
"value" : 7830
},
"end_address" : "Vigo, Pontevedra, España",
"end_location" : {
"lat" : 42.2406168,
"lng" : -8.720694999999999
},
"start_address" : "Lugo, España",
"start_location" : {
"lat" : 43.0082848,
[...]
However, when I try it online i get different geocoded waypoints and, therefore, zero_results.
'types': ['bar', 'establishment', 'food', 'point_of_interest', 'restaurant']}], 'routes': [], 'status': 'ZERO_RESULTS'}
How can I change geocoded_waypoint types??
As I can see from your example you try to get directions between two Spanish cities. However, when you specify only names of cities in origin and destination the service might resolve them to different countries due to ambiguity in parameters. For example, when I execute your request on my server that located in USA the destination Lugo is resolved to place ID ChIJi59iTw6wZIgRvssCUK9Ra84 which is a restaurant with name "Lugo's" located in 107 S Main St, Dickson, TN 37055, USA.
See place details
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJi59iTw6wZIgRvssCUK9Ra84&fields=formatted_address,geometry,name,type&key=YOUR_API_KEY
As origin is located in Spain and destination in USA, the directions service cannot build a driving directions and returns ZERO_RESULTS.
In order to resolve ambiguity you should provide more precise origin and destination parameters or specify a region where you are searching results.
If I add region parameter in request I get expected route between Spanish cities
https://maps.googleapis.com/maps/api/directions/json?origin=Vigo&destination=Lugo&region=ES&key=YOUR_API_KEY
You can see it in directions calculator:
https://directionsdebug.firebaseapp.com/?origin=Vigo&destination=Lugo&region=ES
I hope my answer clarifies your doubt!

Correctly referencing a JSON in Python. Strings versus Integers and Nested items

Sample JSON file below
{
"destination_addresses" : [ "New York, NY, USA" ],
"origin_addresses" : [ "Washington, DC, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mi",
"value" : 361715
},
"duration" : {
"text" : "3 hours 49 mins",
"value" : 13725
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I'm looking to reference the text value for distance and duration. I've done research but i'm still not sure what i'm doing wrong...
I have a work around using several lines of code, but i'm looking for a clean one line solution..
thanks for your help!
If you're using the regular JSON module:
import json
And you're opening your JSON like this:
json_data = open("my_json.json").read()
data = json.loads(json_data)
# Equivalent to:
data = json.load(open("my_json.json"))
# Notice json.load vs. json.loads
Then this should do what you want:
distance_text, duration_text = [data['rows'][0]['elements'][0][key]['text'] for key in ['distance', 'duration']]
Hope this is what you wanted!

Categories

Resources