Example usage for twitter4j Query KILOMETERS

List of usage examples for twitter4j Query KILOMETERS

Introduction

In this page you can find the example usage for twitter4j Query KILOMETERS.

Prototype

Unit KILOMETERS

To view the source code for twitter4j Query KILOMETERS.

Click Source Link

Usage

From source file:ch.schrimpf.core.TwitterCrawler.java

License:Open Source License

/**
 * @param queryString describes keywords and filters
 * @return an initialized Query//w  w w  .  j  av a  2  s .c o  m
 */
private Query initQuery(String queryString) {
    Query query = new Query(queryString);
    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("easyTwitterCrawler.properties"));
        query.setCount(Integer.parseInt(prop.getProperty("queryLimit")));
        query.setLocale(prop.getProperty("locale"));
        query.setLang(prop.getProperty("lang"));
        GeoLocation location = new GeoLocation(Double.parseDouble(prop.getProperty("latitude")),
                Double.parseDouble(prop.getProperty("longitude")));
        double radius = Double.parseDouble(prop.getProperty("radius"));
        query.setGeoCode(location, radius, Query.KILOMETERS);
    } catch (IOException e) {
        // Properties could not be load
        query.setCount(DEFAULT_QUERY_LIMIT);
        query.setLocale(DEFAULT_LOCALE);
        query.setLang(DEFAULT_LANG);
        query.setGeoCode(DEFAULT_GEO_LOCATION, DEFAULT_RADIUS, Query.KILOMETERS);
    }
    return query;
}

From source file:com.fuzuapp.model.resultados.TwitterAdapter.java

@Override
public List<Resultado> getResultados(GeoPoint ponto, double raio) {

    List<Resultado> resultados = new ArrayList();
    try {//from ww w.j  a  v a2 s  . c o m
        Query query = new Query("");
        GeoLocation geo = new GeoLocation(ponto.getLatitude(), ponto.getLongitude());
        query.setGeoCode(geo, raio, Query.KILOMETERS);
        query.resultType(Query.RECENT);
        query.setCount(20);
        QueryResult result = twitter.search(query);

        for (Status status : result.getTweets()) {
            Resultado r = new Resultado();

            r.setDescricao(status.getText());
            r.setUrl("http://twitter.com/statuses/" + String.valueOf(status.getId()));
            r.setNomeUsuario(status.getUser().getName());
            r.setHorario(new SimpleDateFormat("dd/MM HH:mm").format(status.getCreatedAt()));
            r.setFotoUrl(status.getUser().getProfileImageURL());
            //r.setLocal(new GeoPoint(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
            r.setTipo(Resultado.TEXTO);

            resultados.add(r);

        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterAdapter.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultados;
}

From source file:com.javielinux.database.EntitySearch.java

License:Apache License

public Query getQuery(Context cnt) {
    String q = this.getString("words_and");

    if (!this.getString("words_or").equals("")) {
        q += Utils.getQuotedText(this.getString("words_or"), "OR ", false);
    }/*w  w w .j a va2  s.  c  o  m*/

    if (!this.getString("words_not").equals("")) {
        q += Utils.getQuotedText(this.getString("words_not"), "-", true);
    }

    if (!this.getString("from_user").equals("")) {
        q += " from:" + this.getString("from_user");
    }

    if (!this.getString("to_user").equals("")) {
        q += " to:" + this.getString("to_user");
    }

    if (!this.getString("source").equals("")) {
        q += " source:" + this.getString("source");
    }

    if (this.getInt("attitude") == 1)
        q += " :)";
    if (this.getInt("attitude") == 2)
        q += " :(";

    String modLinks = "filter:links";
    String websVideos = "twitvid OR youtube OR vimeo OR youtu.be";
    String webPhotos = "lightbox.com OR mytubo.net OR imgur.com OR instagr.am OR twitpic OR yfrog OR plixi OR twitgoo OR img.ly OR picplz OR lockerz";

    if (this.getInt("filter") == 1)
        q += " " + modLinks;
    if (this.getInt("filter") == 2)
        q += " " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 3)
        q += " " + websVideos + " " + modLinks;
    if (this.getInt("filter") == 4)
        q += " " + websVideos + " OR " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 5)
        q += " source:twitterfeed " + modLinks;
    if (this.getInt("filter") == 6)
        q += " ?";
    if (this.getInt("filter") == 7)
        q += " market.android.com OR androidzoom.com OR androlib.com OR appbrain.com OR bubiloop.com OR yaam.mobi OR slideme.org "
                + modLinks;

    Log.d(Utils.TAG, "Buscando: " + q);

    Query query = new Query(q);

    if (this.getInt("use_geo") == 1) {
        if (this.getInt("type_geo") == 0) { // coordenadas del mapa
            GeoLocation gl = new GeoLocation(this.getDouble("latitude"), this.getDouble("longitude"));
            String unit = Query.KILOMETERS;
            if (this.getInt("type_distance") == 0)
                unit = Query.MILES;
            query.setGeoCode(gl, this.getDouble("distance"), unit);
        }

        if (this.getInt("type_geo") == 1) { // coordenadas del gps
            Location loc = LocationUtils.getLastLocation(cnt);
            if (loc != null) {
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                String unit = Query.KILOMETERS;
                if (this.getInt("type_distance") == 0)
                    unit = Query.MILES;
                query.setGeoCode(gl, this.getDouble("distance"), unit);
            } else {
                mErrorLastQuery = cnt.getString(R.string.no_location);
            }
        }
    }

    PreferenceManager.setDefaultValues(cnt, R.xml.preferences, false);
    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(cnt);

    int count = Integer.parseInt(preference.getString("prf_n_max_download", "60"));
    if (count <= 0)
        count = 60;

    query.setCount(count);

    String lang = "";
    if (!this.getString("lang").equals(""))
        lang = this.getString("lang");
    if (!lang.equals("all"))
        query.setLang(lang);

    // obtener desde donde quiero hacer la consulta

    if (getInt("notifications") == 1) {
        String where = "search_id = " + this.getId() + " AND favorite = 0";
        int nResult = DataFramework.getInstance().getEntityListCount("tweets", where);
        if (nResult > 0) {
            long mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets", where, "date desc")
                    .getLong("tweet_id");
            query.setSinceId(mLastIdNotification);
        }
    }

    //query.setResultType(Query.POPULAR);

    return query;
}

From source file:crawltweets2mongo.MonoThread.java

void getNewTweets(GeoLocation myLoc, double radius) {
    try {//from  w w  w. j  a  v  a2  s  .  c  o m
        Query query = new Query();
        Query.Unit unit = Query.KILOMETERS; // or Query.MILES;
        query.setGeoCode(myLoc, radius, unit);
        if (radius > 200)
            query.setCount(20000);
        else
            query.setCount(20000);

        QueryResult result;
        result = this.twitter.search(query);

        //System.out.println("Getting Tweets. by Geo..");
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {

            BasicDBObject basicObj = new BasicDBObject();
            basicObj.put("user_Rname", tweet.getUser().getName());
            basicObj.put("user_name", tweet.getUser().getScreenName());
            basicObj.put("retweet_count", tweet.getRetweetCount());
            basicObj.put("tweet_followers_count", tweet.getUser().getFollowersCount());

            UserMentionEntity[] mentioned = tweet.getUserMentionEntities();
            basicObj.put("tweet_mentioned_count", mentioned.length);
            basicObj.put("tweet_ID", tweet.getId());
            basicObj.put("tweet_text", tweet.getText());
            Status temp1 = tweet.getRetweetedStatus();
            if (temp1 != null)
                basicObj.put("Re_tweet_ID", temp1.getUser().getId());
            GeoLocation loc = tweet.getGeoLocation();
            if (loc != null) {
                basicObj.put("Latitude", loc.getLatitude());
                basicObj.put("Longitude", loc.getLongitude());
            }
            basicObj.put("CreateTime", tweet.getCreatedAt());
            basicObj.put("FavoriteCount", tweet.getFavoriteCount());
            basicObj.put("user_Id", tweet.getUser().getId());

            if (tweet.getUser().getTimeZone() != null)
                basicObj.put("UsertimeZone", tweet.getUser().getTimeZone());
            if (tweet.getUser().getStatus() != null)
                basicObj.put("UserStatus", tweet.getUser().getStatus());
            //basicObj.put("tweetLocation", tweet.getPlace().getGeometryCoordinates());
            String U_Loc = tweet.getUser().getLocation();
            if (U_Loc != null)
                basicObj.put("userLocation", U_Loc);
            basicObj.put("number_of_rt", tweet.getRetweetCount());
            //basicObj.put("isRetweet", tweet.getPlace().getGeometryCoordinates());                
            //basicObj.put("POS", tweet.getWithheldInCountries());

            if (mentioned.length > 0) {
                basicObj.append("mentions", pickMentions(mentioned));
            }
            try {
                //items.insert(basicObj);
                collection.insert(basicObj);
            } catch (Exception e) {
                //     System.out.println("MongoDB Connection Error : " + e.getMessage());
                //                            loadMenu();
            }
        }
        collection.ensureIndex(new BasicDBObject("tweet_ID", 1), new BasicDBObject("unique", true));
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(MonoThread.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:gui.project2.v1.FXMLDocumentController.java

@FXML
public void searchloaction() throws InterruptedException {
    int maxFollowerCount = 0;
    userslocations = new ArrayList<>();
    nodes = new ArrayList<>();

    GraphicsContext gc = graph.getGraphicsContext2D();
    gc.setFill(Color.GAINSBORO);//  w ww .  j av  a  2s.com
    gc.fillRect(0, 0, 308, 308);
    Twitter twitter;
    twitter = tf.getInstance();
    ArrayList<User> users = new ArrayList<>();
    try {
        Query query = new Query("");

        GeoLocation location;
        location = new GeoLocation(parseDouble(latitude.getText()), parseDouble(longitude.getText()));
        Query.Unit unit = Query.KILOMETERS;
        query.setGeoCode(location, parseDouble(radius.getText()), 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());
                boolean q = false;
                if (userslocations != null && !userslocations.isEmpty()) {
                    for (int i = 0; i < userslocations.size(); i++) {
                        if (userslocations.get(i).getName().equals(tweet.getUser().getScreenName())) {
                            q = true;
                            break;
                        }
                    }
                }

                if (!q && tweet.getGeoLocation() != null) {
                    pair n;
                    String latString = "";
                    String lonString = "";
                    int la = 0;
                    int lo = 0;
                    String geoString = tweet.getGeoLocation().toString();
                    for (int i = 0; i < geoString.length(); i++) {
                        if (geoString.charAt(i) == '=') {
                            if (la == 0) {
                                la = 1;
                            } else if (la == -1) {
                                lo = 1;
                            }
                        } else if (geoString.charAt(i) == ',') {
                            la = -1;
                        } else if (geoString.charAt(i) == '}') {
                            lo = -1;
                        } else if (la == 1) {
                            latString = latString + geoString.charAt(i);
                        } else if (lo == 1) {
                            lonString = lonString + geoString.charAt(i);
                        }
                    }
                    User thisUser;
                    thisUser = tweet.getUser();
                    double lat = parseDouble(latString);
                    double lon = parseDouble(lonString);
                    System.out.println(tweet.getGeoLocation().toString());
                    n = new pair(tweet.getUser().getScreenName(), lat, lon);
                    userslocations.add(n);
                    users.add(thisUser);
                    if (thisUser.getFollowersCount() > maxFollowerCount) {
                        maxFollowerCount = thisUser.getFollowersCount();
                    }
                }

            }
        } while ((query = result.nextQuery()) != null);
        for (int i = 0; i < users.size(); i++) {
            if (i % 14 == 0 && i != 0) {
                Thread.sleep(1000 * 60 * 15 + 30);
            }
            IDs friends;
            friends = twitter.getFriendsIDs(users.get(i).getId(), -1);
            for (long j : friends.getIDs()) {
                for (int k = i + 1; k < users.size(); k++) {
                    if (users.get(k).getId() == j) {
                        nodes.add(users.get(i).getScreenName() + ":" + users.get(k).getScreenName());
                    }
                }
            }
        }

    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    double xmin;
    double xmax;
    double ymin;
    double ymax;
    xmin = userslocations.get(0).getA();
    xmax = userslocations.get(0).getA();
    ymin = userslocations.get(0).getB();
    ymax = userslocations.get(0).getB();
    for (int i = 1; i < userslocations.size(); i++) {
        if (xmin > userslocations.get(i).getA()) {
            xmin = userslocations.get(i).getA();
        }
        if (xmax < userslocations.get(i).getA()) {
            xmax = userslocations.get(i).getA();
        }
        if (ymin > userslocations.get(i).getB()) {
            ymin = userslocations.get(i).getB();
        }
        if (ymax < userslocations.get(i).getB()) {
            ymax = userslocations.get(i).getB();
        }
    }
    for (int i = 0; i < userslocations.size(); i++) {
        if (userslocations.get(i).getA() - xmin >= 0 && userslocations.get(i).getB() - ymin >= 0) {
            gc.setLineWidth(users.get(i).getFollowersCount() / maxFollowerCount * 3 + 1);
            gc.strokeOval((userslocations.get(i).getA() - xmin) / (xmax - xmin) * 300 + 4,
                    (userslocations.get(i).getB() - ymin) / (ymax - ymin) * 300 + 4, 4, 4);
        }

    }
    ObservableList<String> usersLeftList = FXCollections.observableArrayList();
    for (int i = 0; i < users.size() - 1; i++) {
        User k = null;
        for (int j = i + 1; j < users.size(); j++) {
            if (users.get(j).getFollowersCount() > users.get(i).getFollowersCount()) {
                k = users.get(i);
                users.set(i, users.get(j));
                users.set(j, k);
            }
        }
    }
    for (int i = 0; i < users.size() / 5; i++) {
        usersLeftList.add(users.get(i).getScreenName() + " " + users.get(i).getFollowersCount());
    }
    listView.setItems(usersLeftList);
    gc.setLineWidth(1);
    gc.setFill(Color.BLUE);
    for (int i = 0; i < nodes.size(); i++) {
        String user1 = "";
        String user2 = "";
        int p = 0;
        double x1 = 0;
        double x2 = 0;
        double y1 = 0;
        double y2 = 0;
        for (int j = 0; j < nodes.get(i).length(); j++) {
            if (nodes.get(i).charAt(j) == ':') {
                p = 1;
            } else if (p == 0) {
                user1 = user1 + nodes.get(i).charAt(j);
            } else if (p == 1) {
                user2 = user2 + nodes.get(i).charAt(j);
            }
        }
        for (int j = 0; j < userslocations.size(); j++) {
            if (userslocations.get(j).getName().equals(user1)) {
                x1 = (userslocations.get(j).getA() - xmin) / (xmax - xmin) * 300 + 6;
                y1 = (userslocations.get(j).getB() - ymin) / (ymax - ymin) * 300 + 6;
            } else if (userslocations.get(j).getName().equals(user2)) {
                x2 = (userslocations.get(j).getA() - xmin) / (xmax - xmin) * 300 + 6;
                y2 = (userslocations.get(j).getB() - ymin) / (ymax - ymin) * 300 + 6;
            }
        }
        gc.strokeLine(x1, y1, x2, y2);
        gc.fillOval(x1 - 2, y1 - 2, 4, 4);
        gc.fillOval(x2 - 2, y2 - 2, 4, 4);
    }
}

From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java

/**
 * Entry point for a Lappsgrid service./*from  ww w. j a v  a 2s .c  o  m*/
 * <p>
 * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object
 * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container}
 * payload.
 * <p>
 * Errors and exceptions that occur during processing should be wrapped in a {@code Data}
 * object with the discriminator set to http://vocab.lappsgrid.org/ns/error
 * <p>
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br />
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br />
 *
 * @param input A JSON string representing a Data object
 * @return A JSON string containing a Data object with a Container payload.
 */
@Override
public String execute(String input) {
    Data<String> data = Serializer.parse(input, Data.class);
    String discriminator = data.getDiscriminator();

    // Return ERRORS back
    if (Discriminators.Uri.ERROR.equals(discriminator)) {
        return input;
    }

    // Generate an error if the used discriminator is wrong
    if (!Discriminators.Uri.GET.equals(discriminator)) {
        return generateError(
                "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator);
    }

    Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false)
            .build();

    // Authentication using saved keys
    Twitter twitter = new TwitterFactory(config).getInstance();
    String key = readProperty(KEY_PROPERTY);
    if (key == null) {
        return generateError("The Twitter Consumer Key property has not been set.");
    }

    String secret = readProperty(SECRET_PROPERTY);
    if (secret == null) {
        return generateError("The Twitter Consumer Secret property has not been set.");
    }

    twitter.setOAuthConsumer(key, secret);

    try {
        twitter.getOAuth2Token();
    } catch (TwitterException te) {
        String errorData = generateError(te.getMessage());
        logger.error(errorData);
        return errorData;
    }

    // Get query String from data payload
    Query query = new Query(data.getPayload());

    // Set the type to Popular or Recent if specified
    // Results will be Mixed by default.
    if (data.getParameter("type") == "Popular")
        query.setResultType(Query.POPULAR);
    if (data.getParameter("type") == "Recent")
        query.setResultType(Query.RECENT);

    // Get lang string
    String langCode = (String) data.getParameter("lang");

    // Verify the validity of the language code and add it to the query if it's valid
    if (validateLangCode(langCode))
        query.setLang(langCode);

    // Get date strings
    String sinceString = (String) data.getParameter("since");
    String untilString = (String) data.getParameter("until");

    // Verify the format of the date strings and set the parameters to query if correctly given
    if (validateDateFormat(untilString))
        query.setUntil(untilString);
    if (validateDateFormat(sinceString))
        query.setSince(sinceString);

    // Get GeoLocation
    if (data.getParameter("address") != null) {
        String address = (String) data.getParameter("address");
        double radius = (double) data.getParameter("radius");
        if (radius <= 0)
            radius = 10;
        Query.Unit unit = Query.MILES;
        if (data.getParameter("unit") == "km")
            unit = Query.KILOMETERS;
        GeoLocation geoLocation;
        try {
            double[] coordinates = getGeocode(address);
            geoLocation = new GeoLocation(coordinates[0], coordinates[1]);
        } catch (Exception e) {
            String errorData = generateError(e.getMessage());
            logger.error(errorData);
            return errorData;
        }

        query.geoCode(geoLocation, radius, String.valueOf(unit));

    }

    // Get the number of tweets from count parameter, and set it to default = 15 if not specified
    int numberOfTweets;
    try {
        numberOfTweets = (int) data.getParameter("count");
    } catch (NullPointerException e) {
        numberOfTweets = 15;
    }

    // Generate an ArrayList of the wanted number of tweets, and handle possible errors.
    // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed
    ArrayList<Status> allTweets;
    Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter);
    String tweetsDataDisc = tweetsData.getDiscriminator();
    if (Discriminators.Uri.ERROR.equals(tweetsDataDisc))
        return tweetsData.asPrettyJson();

    else {
        allTweets = (ArrayList<Status>) tweetsData.getPayload();
    }

    // Initialize StringBuilder to hold the final string
    StringBuilder builder = new StringBuilder();

    // Append each Status (each tweet) to the initialized builder
    for (Status status : allTweets) {
        String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : "
                + status.getText() + "\n";
        builder.append(single);
    }

    // Output results
    Container container = new Container();
    container.setText(builder.toString());
    Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container);
    return output.asPrettyJson();
}

From source file:org.mixare.utils.TwitterClient.java

License:Open Source License

/**
 * Query the twitter search API using oAuth 2.0
 * @return/*from   ww w .  j  a v  a 2  s. c o m*/
 */
public static String queryData() {
    ConfigurationBuilder cb = new ConfigurationBuilder(); //to be configured in a properties...
    cb.setDebugEnabled(true).setOAuthConsumerKey("mt10dv6tTKacqlm14lw5w")
            .setOAuthConsumerSecret("4kRV1E1XIU3kj4JQj2R5LE1yct0RRaRl9sB5PpPrB0")
            .setOAuthAccessToken("390019380-IQ5VdvUKvxY9JOsTToEU8ElCabebc76H9X2g3QX4")
            .setOAuthAccessTokenSecret("ghJn4LTfDr7uHUCsbt6ycmpeVTwwpa3hZnXyEjyZvs");
    cb.setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    Query query = new Query();
    query = query.geoCode(new GeoLocation(lat, lon), rad, Query.KILOMETERS);

    String jsonArrayAsString = "{\"results\":[";//start
    try {
        QueryResult result = twitter.search(query);
        int size = 0;
        for (Status status : result.getTweets()) {
            {
                if (status.getGeoLocation() != null) {
                    String jsonSingleObject = DataObjectFactory.getRawJSON(status);
                    if (size == 0)
                        jsonArrayAsString += jsonSingleObject;
                    else
                        jsonArrayAsString += "," + jsonSingleObject;
                    size++;
                }
            }
        }
        jsonArrayAsString += "]}";//close array
        return jsonArrayAsString;
    } catch (Exception e) {
        Log.e(Config.TAG, "Error querying twitter data :" + e);
        e.printStackTrace();
    }
    return null;
}

From source file:org.wandora.application.tools.extractors.twitter.TwitterExtractorUI.java

License:Open Source License

public Query[] getSearchQuery() {
    String query = queryTextField.getText();
    String lang = langTextField.getText().trim();
    String until = untilTextField.getText().trim();
    String since = sinceTextField.getText().trim();
    GeoLocation geol = solveGeoLocation();
    double distance = solveDistance();
    ArrayList<Query> queries = new ArrayList();

    Query q = new Query(query);

    if (lang.length() > 0)
        q.setLang(lang);/*from   w w  w.j a  va  2  s . co m*/
    if (until.length() > 0)
        q.setUntil(until);
    if (since.length() > 0)
        q.setSince(since);
    if (geol != null)
        q.setGeoCode(geol, distance, Query.KILOMETERS);

    q.count(100);

    queries.add(q);

    return queries.toArray(new Query[] {});
}

From source file:twitterrest.GeoSearch.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    // ?/*from   ww  w  .j ava2  s.co  m*/
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter twitter = new TwitterFactory(configuration).getInstance();
    Query query = new Query();

    // ?????10kmIP??????      
    GeoLocation geo = new GeoLocation(35.69384, 139.703549);
    query.setGeoCode(geo, 10.0, Query.KILOMETERS);

    // 
    QueryResult result = twitter.search(query);

    // ???Tweet??placegeoLocation??????
    for (Status tweet : result.getTweets()) {
        System.out.println(tweet.getText());
        System.out.println(tweet.getPlace() + " : " + tweet.getGeoLocation());
    }
}

From source file:uk.ac.susx.tag.method51.twitter.params.QueryParams.java

License:Apache License

public Query buildQuery() throws SQLException {
    List<String> keywords = getKeywords();

    if (keywords.size() == 0 && getLocation().size() == 0) {
        throw new RuntimeException("No keywords or locations provided");
    }// www . j a v a2 s  . c  o m

    final String q;

    if (keywords.size() > 1) {
        q = "\"" + StringUtils.join(keywords, "\" OR \"") + "\"";
    } else {
        q = keywords.get(0);
    }

    //LOG.info("Searching keywords: {}", q);
    //LOG.info("Query length: {}", q.length());

    Query query = new Query(q);
    query.setCount(100);
    query.setResultType(Query.RECENT);

    if (getAcceptedLanguages().size() > 0) {
        query.setLang(StringUtils.join(getAcceptedLanguages(), ","));
    }

    if (getUntilId() != null) {
        query.setMaxId(getUntilId());
    }

    if (getSinceId() != null) {
        query.setSinceId(getSinceId());

    } else if (getSinceMaxId()) {
        try (Connection con = dbParams.get().buildConnection()) {
            long maxId = Util.getMaxID(con, getMysqlTweetOutputTable());
            query.setSinceId(maxId);
            LOG.info("Determined {} as max id, searching since that.", maxId);
        }
    }

    if (getSinceId() == null && getSinceDate() != null) {
        long approxSinceId = Util.getMinSnowflakeId(getSinceDate());
        query.setSinceId(approxSinceId);
        LOG.info("Determined min Snowflake ID {}", approxSinceId);
    }

    if (getUntilId() == null && getUntilDate() != null) {
        long approxUntilId = Util.getMaxSnowflakeId(getUntilDate());
        query.setMaxId(approxUntilId);
        LOG.info("Determined max Snowflake ID {}", approxUntilId);
    }

    if (getLocation().size() == 1) {
        try {
            String[] geo = getLocation().get(0).split("\\|");

            query.setGeoCode(new GeoLocation(Double.parseDouble(geo[0]), Double.parseDouble(geo[1])),
                    Double.parseDouble(geo[2]), Query.KILOMETERS);

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("invalid location param " + getLocation().get(0), e);
        }
    }

    return query;
}