Python – API.reverse_geocode() in Tweepy
Last Updated :
11 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
API.reverse_geocode()
The reverse_geocode()
method of the API
class in Tweepy module is used to fetches the nearby locations for the provided coordinates.
Syntax : API.reverse_geocode(lat, long, accuracy, granularity, max_results)
Parameters :
- lat : latitude of the location.
- long : longitude of the location.
- accuracy : Specify the “region” in which to search.
- granularity : Assumed to be neighborhood by default, can also be city..
- max_results : maximum number of results to fetch.
Returns : a list of objects of class Place
Example 1 :
import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
lat = 28
long = 77
locations = api.reverse_geocode(lat, long )
print ( str ( len (locations)) + " location(s) is / are fetched." )
print ( "\nThe location(s) is / are :" )
for location in locations:
print (location.name)
|
Output :
2 location(s) is/are fetched.
The location(s) is/are :
Haryana
India
Example 2 : Exception is raised when giving invalid coordinates.
lat = 200
long = 123
locations = api.reverse_geocode(lat, long )
|
Output :
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\tweepytesting.py", line 28, in
locations = api.reverse_geocode(lat, long)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\binder.py", line 250, in _call
return method.execute()
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\binder.py", line 236, in execute
result = self.parser.parse(self, resp.text)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\parsers.py", line 98, in parse
result = model.parse_list(method.api, json)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\tweepy\models.py", line 481, in parse_list
item_list = json_list['result']['places']
KeyError: 'result'
Share your thoughts in the comments
Please Login to comment...