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®ion=ES&key=YOUR_API_KEY
You can see it in directions calculator:
https://directionsdebug.firebaseapp.com/?origin=Vigo&destination=Lugo®ion=ES
I hope my answer clarifies your doubt!
Related
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)
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!
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
I am attempting to parse some JSON that I am receiving from a RESTful API, but I am having trouble accessing the data in Python because it appears that there is an empty property name.
A sample of the JSON returned:
{
"extractorData" : {
"url" : "RetreivedDataURL",
"resourceId" : "e38e1a7dd8f23dffbc77baf2d14ee500",
"data" : [ {
"group" : [ {
"CaseNumber" : [ {
"text" : "PO-1994-1350",
"href" : "http://www.referenceURL.net"
} ],
"DateFiled" : [ {
"text" : "03/11/1994"
} ],
"CaseDescription" : [ {
"text" : "Mary v. JONES"
} ],
"FoundParty" : [ {
"text" : "Lastname, MARY BETH (Plaintiff)"
} ]
}, {
"CaseNumber" : [ {
"text" : "NP-1998-2194",
"href" : "http://www.referenceURL.net"
}, {
"text" : "FD-1998-2310",
"href" : "http://www.referenceURL.net"
} ],
"DateFiled" : [ {
"text" : "08/13/1993"
}, {
"text" : "06/02/1998"
} ],
"CaseDescription" : [ {
"text" : "IN RE: NOTARY PUBLIC VS REDACTED"
}, {
"text" : "REDACTED"
} ],
"FoundParty" : [ {
"text" : "Lastname, MARY H (Plaintiff)"
}, {
"text" : "Lastname, MARY BETH (Defendant)"
} ]
} ]
} ]
And the Python code I am attempting to use
import requests
import json
FirstName = raw_input("Please Enter First name: ")
LastName = raw_input("Please Enter Last Name: ")
with requests.Session() as c:
url = ('https://www.requestURL.net/?name={}&lastname={}').format(LastName, FirstName)
page = c.get(url)
data = page.content
theJSON = json.loads(data)
def myprint(d):
stack = d.items()
while stack:
k, v = stack.pop()
if isinstance(v, dict):
stack.extend(v.iteritems())
else:
print("%s: %s" % (k, v))
print myprint(theJSON["extractorData"]["data"]["group"])
I get the error:
TypeError: list indices must be integers, not str
I am new to parsing Python and more than simple python in general so excuse my ignorance. But what leads me to believe that it is an empty property is that when I use a tool to view the JSON visually online, I get empty brackets, Like so:
Any help parsing this data into text would be of great help.
EDIT: Now I am able to reference a certain node with this code:
for d in group:
print group[0]['CaseNumber'][0]["text"]
But now how can I iterate over all the dictionaries listed in the group property to list all the nodes labeled "CaseNumber" because it should exist in every one of them. e.g
print group[0]['CaseNumber'][0]["text"]
then
for d in group:
print group[1]['CaseNumber'][0]["text"]
and so on and so forth. Perhaps incrementing some sort of integer until it reaches the end? I am not quite sure.
If you look at json carefully the data key that you are accessing is actually a list, but data['group'] is trying to access it as if it were a dictionary, which is raising the TypeError.
To minify your json it is something like this
{
"extractorData": {
"url": "string",
"resourceId": "string",
"data": [{
"group": []
}]
}
}
So if you want to access group, you should first retrieve data which is a list.
data = sample['extractorData']['data']
then you can iterate over data and get group within it
for d in data:
group = d['group']
I hope this clarifies things a bit for you.
I am using this approach to get the comments on page data.Its working fine,but I need to dump the data into MongoDB. Using this approach data is inserted but as a single document.I want to store that every comment should have a separate document with the information I am getting from the API.
from facepy import GraphAPI
import json
import pymongo
import json
connection = pymongo.MongoClient("mongodb://localhost")
facebook = connection.facebook
commen = facebook.comments
access = ''
#message
graph = GraphAPI(access)
page_id= 'micromaxinfo'
datas= graph.get(page_id+'/posts?fields=comments,created_time', page=True, retry=5)
posts=[]
for data in datas:
print data
commen.insert(data)
break
Output Stored in MongoDB:
{
"created_time" : "2015-11-04T08:04:14+0000",
"id" : "120735417936636_1090909150919253",
"comments" : {
"paging" : {
"cursors" : {
"after" : "WTI5dGJXVnVkRjlqZFhKemIzSTZNVEE1TVRReE5ESTVOelV6TlRRd05Ub3hORFEyTnpFNU5UTTU=",
"before" : "WTI5dGJXVnVkRjlqZFhKemIzSTZNVEE1TURrd09UVTRNRGt4T1RJeE1Eb3hORFEyTmpJME16Z3g="
}
},
"data" : [
{
"created_time" : "2015-11-04T08:06:21+0000",
"message" : "my favorite mobiles on canvas silver",
"from" : {
"name" : "Velchamy Alagar",
"id" : "828304797279948"
},
"id" : "1090909130919255_1090909580919210"
},
{
"created_time" : "2015-11-04T08:10:13+0000",
"message" : "Micromax mob. मैने कुछ दिन पहले Micromax Bolt D321 mob. खरिद लिया | Bt मेरा मोबा. बहुत गरम होता है Without internate. और internate MB कम समय मेँ ज्यादा खर्च होती है | कोई तो help करो.",
"from" : {
"name" : "Amit Gangurde",
"id" : "1637669796485258"
},
"id" : "1090909130919255_1090910364252465"
},
{
"created_time" : "2015-11-04T08:10:27+0000",
"message" : "Nice phones.",
"from" : {
"name" : "Nayan Chavda",
"id" : "1678393592373659"
},
"id" : "1090909130919255_1090910400919128"
},
{
"created_time" : "2015-11-04T08:10:54+0000",
"message" : "sir micromax bolt a089 mobile ki battery price kitna. #micromax mobile",
"from" : {
"name" : "Arit Singha Roy",
"id" : "848776351903695"
},
So technically I want to store only information coming in data field:
{
"created_time" : "2015-11-04T08:10:54+0000",
"message" : "sir micromax bolt a089 mobile ki battery price kitna. #micromax mobile",
"from" : {
"name" : "Arit Singha Roy",
"id" : "848776351903695"
}
How to get this into my database?
You can use the pentaho data integration open source ETL tool for this. I use it to store specific fields from the JSON output for tweets.
Select the fields you want to parse from the JSON and select an output as csv or table output in Oracle etc.
Hope this helps