Python and vsCode, using google maps API
I have copied a program from a person on the internet to find all the businesses in my local area, but the returned data doesn't seem correct.
I first tried to search by keyword, and this returned lots of results, but not the type of business I wanted. I deleted this variable, and instead used an opennow variable. This returned only one result, and it was the town I had searched in, not a business. Could you have a look through the code and see if I have gone wrong?
The API
map_client = googlemaps.Client(API_KEY)
location = (54.970121, -2.101585)
distance = (1)
business_list= []
response = map_client.places_nearby(
location=location,
radius=distance,
)
business_list.extend(response.get('results'))
next_page_token = response.get('next_page_token')
while next_page_token:
time.sleep(2)
response = map_client.places_nearby(
location=location,
radius=distance,
opennow=True,
page_token=next_page_token
)
business_list.extend(response.get('results'))
next_page_token = response.get('next_page_token')
df = pd.DataFrame(business_list)
df['url'] = 'www.google.com/maps/place/?q=place_id:' + df['place_id']
df.to_excel('Toby Buisness.xlsx', index=False)`
Thanks very much
Your Radius for Nearby Search is too small for it to search anything else
I hope you take time to read the Places API documentation and also the Python Client Library for Google Maps to better understand the code you copied.
Now the reason why it is only returning a single result, is because you have this: distance = (1). This variable is used on your response as the value for the parameter radius on your map_client.places_nearby.
If you read the Python Client Library, it says there:
radius (int) – Distance in meters within which to bias results.
And looking at your code, this means that your radius for search is only at 1 meter. Which explains why you are only returning a single result because no other place is in range except the place within its 1 meter range, and if you have not specified any type, of course it will return the name of the vicinity that it is in. In your case, Hexham UK.
So I tried your code and used a radius of 1000 meters and got more than 1 result. Here's the sample code:
import googlemaps
map_client = googlemaps.Client('YOUR_API_KEY_HERE')
location = '54.970121, -2.101585'
distance = 1000
business_list = []
response = map_client.places_nearby(
location=location,
radius=distance,
type='restaurant'
)
business_list.extend(response.get('results'))
print(len(business_list))
Like I said before, please read the documentation because the parameter you used opennow is invalid and the correct one is open_now. Also you can try to use type parameter I used on my example to search for specific results.
Here's a link to the list of types that you can use on Nearby Search: Table 1 Place Types.
Lastly, please make sure that your use case is within the bounds of their Terms of Service (In the case of scraping/caching Google Maps Data) to avoid problems with your app in the future. As I am not a legal expert, I suggest you take time to read their terms in these links: 3.2.3 Restrictions Against Misusing the Services / Places API Specific Terms.
I hope this helps!
Related
I am developing an app in which I am getting the list of ATM's near by the user. For that I am using Google Places API, but every time it returns 20 result only. I want to get more results. In the API doc it is mention that it will return 20 result but I would like to know is there any way I can get more data or I have to create my own database for that?
Also what I found in the API is that it does not have all the ATM's for India. The information is also not accurate for some of the locations. So Please suggest me some idea for that I should use my own database or not?
I know that I can register places in the Google Places but there is the problem that every time it returns only 20 result. If anyhow this problem is resolved then it will be great to use the Places API..
Please kindly help me.....
As per the documentation:
https://developers.google.com/places/web-service/search#PlaceSearchResponses
EDIT: Place API now supports pagination of up to 60 results. See below for details.
The Places API will return up to 20 establishments per query; however, each search can return as many as 60 results, split across three pages. If your search will return more than 20, then the search response will include an additional parameter — next_page_token. Pass the value of next_page_token to the page_token parameter of a new place search to see the next set of 20 results.
There is also strict terms of service that specify you cant Pre-Fetch, Cache, or Store Content unless it is the content identifier or key you are permitted to store i.e. reference token from a places search:
https://cloud.google.com/maps-platform/terms/?_ga=#3-license
In regards to not being able to find ATM's in India. All places are categorized under the type establishment until Google has enough metadata about a place to categorize it under more specific place types like ATM, cafe, bar etc. A work around that may find more results is to use the keyword parameter in your request with something like 'ATM', 'bank' or 'finance' as the value.
As per the documentation:
https://developers.google.com/places/web-service/search#PlaceSearchRequests
The keyword parameter is matched against all available fields, including but not limited to name, type, and address, as well as customer reviews and other third-party content.
Google API fetches the 20 Result in one page suppose you want to use the next page 20 result then we use the next_page_token from google first page xml as a result.
1) https://maps.googleapis.com/maps/api/place/search/xml?location=Enter latitude,Enter Longitude&radius=10000&types=store&hasNextPage=true&nextPage()=true&sensor=false&key=Enter Google_Map_key
in second step you use the first page's next_page_token data
2)https://maps.googleapis.com/maps/api/place/search/xml?location=Enter Latitude,Enter Longitude&radius=10000&types=store&hasNextPage=true&nextPage()=true&sensor=false&key=enter google_map_key &pagetoken="Enter the first page token Value"
You can do this by using Google API JAVA Client - Here is an example using the java client for getting all the 60 results.
public PlacesList search(double latitude, double longitude, double radius, String types)
throws Exception {
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory
.buildGetRequest(new GenericUrl("https://maps.googleapis.com/maps/api/place/search/json?"));
request.getUrl().put("key", YOUR_API_KEY);
request.getUrl().put("location", latitude + "," + longitude);
request.getUrl().put("radius", radius);
request.getUrl().put("sensor", "false");
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
if(list.next_page_token!=null || list.next_page_token!=""){
Thread.sleep(4000);
/*Since the token can be used after a short time it has been generated*/
request.getUrl().put("pagetoken",list.next_page_token);
PlacesList temp = request.execute().parseAs(PlacesList.class);
list.results.addAll(temp.results);
if(temp.next_page_token!=null||temp.next_page_token!=""){
Thread.sleep(4000);
request.getUrl().put("pagetoken",temp.next_page_token);
PlacesList tempList = request.execute().parseAs(PlacesList.class);
list.results.addAll(tempList.results);
}
}
return list;
} catch (HttpResponseException e) {
return null;
}
}
Radar Search doesn't work anymore because it no longer exists: https://cloud.google.com/blog/products/maps-platform/announcing-deprecation-of-place-add
see: https://stackoverflow.com/a/48171023/9903
On the Google places page on: https://developers.google.com/places/documentation/search
Under 'Radar Search Requests' it states that using: https://maps.googleapis.com/maps/api/place/radarsearch/output?parameters
you get 200 results using this call, but note that each call uses 5 requests against your quota.
Please try below url with below parameters
URL = "http://www.google.com/maps?q=restaurant&ie=UTF8&hl=en&sll=0.000000,0.000000&sspn=0.000000,0.000000&vps=3&sa=N&start=20"
Where start = No of results say for instance start from 0 or 10 0r 20 –
You can get the more results from next page token:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=[your search key word]&location=latitude,longitude&radius=value&key=[your API key]&next_page_token=next_page_token value
I'm quite a newbie in Python espescially to use Gmaps API to get place details.
I want to search for places with this parameters:
places_result = gmaps.places_nearby(location=' -6.880270,107.60794', radius = 300, type = 'cafe')
But actually i want to get many data as i can in the specific lat/lng and radius. So, I try to get new parameters that google api has provided. That's page_token. This is the detail of documentation:
pagetoken — Returns up to 20 results from a previously run search. Setting a pagetoken parameter will execute a search with the same parameters used previously — all parameters other than pagetoken will be ignored.
https://developers.google.com/places/web-service/search
So i tried to get more data (Next page data) with this function:
places_result = gmaps.places_nearby(location=' -6.880270,107.60794', radius = 300, type = 'cafe')
time.sleep(5)
place_result = gmaps.places_nearby(page_token = places_result['next_page_token'])
And this is my whole output function:
for place in places_result['results']:
my_place_id = place['place_id']
my_fields = ['name','formatted_address','business_status','rating','user_ratings_total','formatted_phone_number']
places_details = gmaps.place(place_id= my_place_id , fields= my_fields)
pprint.pprint(places_details['result'])
But unfortunately when i start to running i only get 20 (Max) data of place details. I don't know whether my function of page token parameter it's true or not, because the output can't get more than 20 data.
I'm very appreciate for anyone who can give me an advice to solve the problem. Thank you very much :)
As stated on the documentation here:
By default, each Nearby Search or Text Search returns up to 20 establishment results per query; however, each search can return as many as 60 results, split across three pages.
So basically, what you are currently experiencing is an intended behavior. There is no way for you to get more than 20 results in a single nearby search query.
If a next_page_token was returned upon sending your first nearby search query, then, this means that a second page with results is available.
To access this second page of results, then just like what you did, you just have to send another nearby search request, but use the pagetoken parameter this time, and set its value with the next_page_token you got from the first response.
And if the next_page_token also exists on the response of your second nearby search query, then this means that the third (and the last) page of the result is also available. You could access the third page of results using the same way you accessed the second page.
Going back to your query, I tried the parameters you've specified but I could only get around 9 results. Is it intended that your radius parameter is only set at 300 meters?
These days I encounter a really weird problem and cannot solve it.Please help!
I want to use google map api to get the longitude and latitude of an address.Here is my definition of the function to request api:
def get_coordinates(df):
if pd.notnull(df['geocode']):
address=df['geocode']
response = requests.get("https://maps.googleapis.com/maps/api/geocode/json?address="
+ address+"&key=my-key")
json_response = response.json()
if len(json_response['results'])==0:
return 'None'
else:
coordinates=json_response['results'][0]['geometry']['location']
latitude=coordinates['lat']
longitude=coordinates['lng']
l_l=[latitude, longitude]
return l_l
else:
return 'None'
I store the address in a dataframe.
Then I can use df.apply to request api for each address:
test2['coor1'] = test2.apply(get_coordinates,axis = 1)
But then the really weird thing is: I know that most of these address should be in Brazil, but when I use scatter to plot them, I notice many of the point are out of Brazil. So I guess there is something wrong with api request.Then I run apply again and this time, some address get a totally different location from the last time. I have no idea why. I wonder if someone had the same issue before.Thanks a lot!
I want to get all restaurants in London by using python 3.5 and the module googleplaces with the Google Places API. I read the googleplaces documentation and searched here, but I don't get it. Here is my code so far:
from googleplaces import GooglePlaces, types, lang
API_KEY = 'XXXCODEXXX'
google_places = GooglePlaces(API_KEY)
query_result = google_places.nearby_search(
location='London', keyword='Restaurants',
radius=1000, types=[types.TYPE_RESTAURANT])
if query_result.has_attributions:
print query_result.html_attributions
for place in query_result.places:
place.get_details()
print place.rating
The code doesn't work. What can I do to get a list with all restaurants in this area?
It'll be better if you drop the keyword parameter, types already searches for restaurants.
Bear in mind the Places API (as other Google Maps APIs) is not a database, it will not return all results that match. Actually returns only 20, and you can get an extra 40 or so, but that's all.
If I'm reading the GooglePlaces correctly, your code will send an API request such like:
http://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.507351,-0.127758&radius=1000&types=restaurant&keyword=Restaurants&key=YOUR_API_KEY
If you just drop the keyword parameter, it'll be like:
http://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.507351,-0.127758&radius=1000&types=restaurant&key=YOUR_API_KEY
The difference is subtle: keyword=Restaurants will make the API match results that have the word "Restaurants" in their name, address, etc. Some of these may not be restaurants (and will be discarded), while some actual restaurants may not have the word "Restaurants" in them.
Try to change city value by latitude and longitude and it's not necessary to put the keyword because you are specified that on Type try to put this code it's work for me :
query_result = google_places.nearby_search(
lat_lng={'lat': 46.1667, 'lng': -1.15},
radius=5000,
types=[types.TYPE_RESTAURANT] or [types.TYPE_CAFE] or [type.TYPE_BAR] or [type.TYPE_CASINO])
The only thing missing is as the error says, parentheses (). Your code should be
if query_result.has_attributions:
print (query_result.html_attributions)
I havent used Python before but, am told this would be a good language to use for this process. I have a list of Lat/ Long coordinates that i need to convert into a business name. Any ideas where i might find documentation on how to complete this process?
Example:
Doc: LatLong.txt (Has a list of lat / long seperated by columns)
I need to run that list against the Places API with a max radius of 30 and return any businesses (BusinessName, Addy, Phone, etc.) within that radius.
from googleplaces import googleplaces
YOUR_API_KEY = 'aa262fad30e663fca7c7a2be9354fe9984f0b5f2'
google_places = googleplaces(YOUR_API_KEY)
query_result = google_places.nearby_search(lat_lng=41.802893, -89.649930,radius=20000)
for place in query_result.places:
print (place.name)
print (place.geo_location)
print (place.reference)
place.get_details()
print (place.local_phone_number)
print (place.international_phone_number)
print (place.webite)
print (place.url)
is what im playing around with..
Google has some pretty good documentation for getting started:
https://developers.google.com/places/training/basic-place-search
Also this answer may help: https://stackoverflow.com/a/21924452/1393496
You should edit your question and include more detail, what have you tried? what worked? what didn't work?