Search code examples
javatwittergeolocationjerseytwitter4j

Twitter - Query for tweets within a radius of a particular GeoLocation


I am trying to form a query to the Twitter REST API. Is there a way to pass gps coordinates into the query and return tweets that are in a particular radius of that location.


Solution

  • Try this code below. Before trying it, you have to put some values into keyword, latitude, longitude, and radius. keyword is what you search about and I think you can understand what other values mean.

    try {
            Query query = new Query(keyword); //
    
            GeoLocation location = new GeoLocation(latitude, longitude);
            String unit = Query.KILOMETERS; // or Query.MILES;
            query.setGeoCode(location, radius, unit);
    
            QueryResult result; 
    
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
    
                for (Status tweet : tweets) {
                    System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
    
            } while ((query = result.nextQuery()) != null);
    
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }