Tuesday, June 16, 2026
HomeLanguagesPython – API.trends_closest() in Tweepy

Python – API.trends_closest() in Tweepy

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.trends_closest()

The trends_closest() method of the API class in Tweepy module is used to fetches the locations that Twitter has trending topic information for.

Syntax : API.trends_closest(lat, long)

Parameters :

  • lat : latitude of the location.
  • long : longitude of the location.

Returns : an object of class JSON

Example 1 : Using the trends_closest() method for Delhi.




# import the module
import tweepy
  
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
  
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  
# set access to user's access key and access secret 
auth.set_access_token(access_token, access_token_secret)
  
# calling the api 
api = tweepy.API(auth)
  
# coordinates of Delhi
lat = 28
long = 77
  
# fetching the locations
locations = api.trends_closest(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 :

1 location(s) is/are fetched.

The location(s) is/are :
Delhi

Example 2 : Exception is raised when giving invalid coordinates.




# invalid coordinates
lat = 200
long = 114
  
# fetching the locations
locations = api.trends_closest(lat, long)


Output :

    raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: [{'code': 3, 'message': 'Invalid coordinates.'}]
Last Updated :
11 Jun, 2020
Like Article
Save Article

<!–

–>

Similar Reads
Related Tutorials
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS