2014-03-30 111 views

回答

0

試試下面這段代碼。在嘗試之前,您必須將一些值寫入keywordlatitude,longituderadiuskeyword是您搜索的內容,我認爲您可以理解其他值的含義。

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); 
    } 
1

使用GET search/tweets端點,您可以指定地理編碼和半徑以從該區域內獲取一組Tweets。參數值如下:緯度,經度,半徑。

例:37.781157,-122.398720,1mi

+0

是否有使用Twitter4J Query做到這一點? – user3461851

0

基於@Seohyun Choi的回答,這是完整的帶驗證碼的java代碼。 在編譯此代碼之前,請在路徑中添加twitter4j-core-3.0.5.jar

import java.util.List; 
import twitter4j.GeoLocation; 
import twitter4j.Query; 
import twitter4j.QueryResult; 
import twitter4j.Status; 
import twitter4j.Twitter; 
import twitter4j.TwitterException; 
import twitter4j.TwitterFactory; 
import twitter4j.conf.ConfigurationBuilder; 

public class TweetsInParticularLocation { 
    private static final String TWITTER_CONSUMER_KEY = "****"; 
    private static final String TWITTER_SECRET_KEY = "*****"; 
    private static final String TWITTER_ACCESS_TOKEN = "****"; 
    private static final String TWITTER_ACCESS_TOKEN_SECRET = "***"; 
public static void main(String arg[]) 
{ 
    ConfigurationBuilder cb = new ConfigurationBuilder(); 
    cb.setDebugEnabled(true) 
     .setOAuthConsumerKey(TWITTER_CONSUMER_KEY) 
     .setOAuthConsumerSecret(TWITTER_SECRET_KEY) 
     .setOAuthAccessToken(TWITTER_ACCESS_TOKEN) 
     .setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET); 
    TwitterFactory tf = new TwitterFactory(cb.build()); 
    Twitter twitter = tf.getInstance(); 

    try { 
     Query query = new Query("India"); // 

     GeoLocation location = new GeoLocation(20.593684, 78.962880); //latitude, longitude 
     String unit = Query.KILOMETERS; // or Query.MILES; 
     query.setGeoCode(location, 1, unit); //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); 
    } 

}}