Get location information using twitter api

Asked 2 years ago, Updated 2 years ago, 66 views

I'd like to check where the timeline containing specific characters was created.
In this case, which twitter api should I use to make it possible?

twitter geographical-information

2022-09-30 18:34

2 Answers

Search for tweets

You can use the .
You can limit it to tweets with geo attributes and use geocode.Arguments are in the form latitude, longitude, and distance km.

Sample code is Ruby.

#!/usr/bin/env ruby
# coding —utf-8

gem 'twitter', '>=5.0.0' # twitter gem version must be 5 or higher
require'twitter'

client=Twitter::REST::Client.new(
# Register API Access Tokens
  consumer_key: 'TWITTER_CONSUMER_KEY',
  consumer_secret: 'TWITTER_CONSUMER_SECRET',
  access_token: 'ACCESS_TOKEN',
  access_token_secret: 'ACCESS_TOKEN_SECRET'
)
since_id = nil 

loop do
  tweets=client.search(
    "love", # Search keyword to "love"
#    geocode: "40.7033121, -73.979681, 10km", #around New York
    count: 100,# Number of read tweets (API limit is 100)
    since_id:since_id# Specify the start-to-read id of the tweet to avoid retrieving the same tweet
  )
  since_id=tweets.first.id if tweets.first
  tweets.take(100).reverse.each do|tw|
    next if tw.geo.lat.nil?# If the tweet does not contain latitude, go to the next tweet
                            # Not required to include geocode in client.search argument
    puts"#{tw.place.name},#{tw.place.country}(#{tw.geo.lat},#{tw.geo.long})@#{tw.created_at}\n@#{tw.user.screen_name}(@#{tw.user.location}):#{tw.text}\n---"
    # Output Tweet Search Results in 1 Tweet 2 Lines
    # City, Country (latitude, longitude) @ Tweet Time
    # @Account Name (@Account registered place name): Tweet body 
  end
  sleep10#Repeat every 10 seconds
end

After a little explanation of the script,

  • tw instance contains information for each tweet. It's almost the same as what the API returned in JSON.
  • tw.place.name returns "name" for JSON's "place", "code" for "place", "country" for "place", "code>tw.geo.lat returns the first (or latitude) of "coordinates" for "geo", and "code>tw.geo.long returns "coins" for "goins" (or second) respectively. If
  • geocode is specified, the search keyword is empty but API-wise OK. (Note: The Search API|Twitter Developers)
  • If you look at JSON in languages other than Ruby, you will be able to get the history.

Example JSON returned from API:

{
  "created_at":"Tue Feb 03 14:36:14 +0000 2015",
  "id":562620584031318018,
  "id_str":"562620584031318018",
  " text " : " Krzykowski, but is being @ the South East Asia _ _   # Get Well Soon Beng Ta   gaishi , ware 们 Mr.) was Chido 你 yuu ta 幺 a structure would make every effort, ; provided, however, that what is it healthy sara zyuu you 啊! shin kokoro 疼 你 们! Please   Kitakinki Tango Railway Corporation Ippyo ea you  , CrunchGear, logistics, and business process Lseb Below client-limit   been been installed successfully! employee!   of Lloyd Brightcove   ",
  "source":"Twitter for Android","
  truncated":false,
  "in_reply_to_status_id":null,
  "in_reply_to_status_id_str":null,
  "in_reply_to_user_id":2483888760,
  "in_reply_to_user_id_str":"2483888760",
  "in_reply_to_screen_name":"hztttao____",
  "user":{
    "id":246864766,
    "id_str":"246864766",
    "name":"tsinychong",
    "screen_name": "tsinyjong",
    "location": "Tawau, Sabah, East Malaysia",
    "profile_location": null,
    "description": "I am a Malaysian Chinese lady. I was attracted by Suju's & EXO's songs & dancing, that's why i'm here." ,
    "url"—Null,
    "entities":{"description":{"urls":[]}},
    "protected": false,
    "followers_count"—6,
    "friends_count": 72,
    "listed_count": 0,
    "created_at": "Thu Feb 03 16:36:39 + 0000 2011",
    "favours_count"—7,
    "utc_offset": 28800,
    "time_zone": "Kuala Lumpur",
    "geo_enabled": true,
    "verified": false,
    "status_count": 1261,
    "lang": "en",
    "contributors_enabled": false,
    "is_translator": false,
    "is_translation_enabled": false,
    "profile_background_color": "EBEBEBEB",
    "profile_background_image_url": "http://abs.twimg.com/images/themes/theme7/bg.gif",
    "profile_background_image_url_https":"https://abs.twimg.com/images/themes/theme7/bg.gif",
    "profile_background_tile": false, "profile_image_url": "http://abs.twimg.com/sticky/default_profile_images/default_profile_1_normal.png",
    "profile_image_url_https": "https://abs.twimg.com/sticky/default_profile_images/default_profile_1_normal.png",
    "profile_link_color": "990000",
    "profile_sidebar_border_color": "DFDFDF",
    "profile_sidebar_fill_color": "F3F3F3",
    "profile_text_color": "33333",
    "profile_use_background_image": true,
    "default_profile": false,
    "default_profile_image": true,
    "following": false,
    "follow_request_sent": false,
    "notifications"—false
  },
  "geo": {"type": "Point", "coordinates": [4.262577, 117.9022693]},
  "coordinates": {"type": "Point", "coordinates": [117.9022693, 4.262577]},
  "place": {
    "id": "eeb42e1fdfb3cfe4",
    "url": "https://api.twitter.com/1.1/geo/id/eeb42e1fdfb3cfe4.json",
    "place_type": "city",
    "name": "Tawau",
    "full_name": "Tawau, Sabah",
    "country_code": "MY",
    "country": "Malaysia",
    "contained_within": [ ],
    "bounding_box": {
      "type": "Polygon",
      "coordinates": [[
        [116.9334819,4.1657558],
        [118.3555885,4.1657558],
        [118.3555885,4.7962486],
        [116.9334819,4.7962486]
      ]]
    },
    "attributes": {}
  },
  "contributors": null,
  "retweet_count": 0,
  "favorite_count": 0,
  "entities": {
    "hashtags":[{"text":"GetWellSoonTao", "indices":[13,28]}],
    "symbols": [ ],
    "user_mentions": [{
      "screen_name": "hztttao___",
      "name": "EXO-TAO Yellow Ribbon",
      "id" : 2483888760,
      "id_str": "2483888760",
      "indices": [0,12]
    }],
    "urls": [ ]
  },
  "favorited": false,
  "retweeted": false,
  "lang": "zh"
}

Sample Results:

Tawau, Malaysia (4.262577, 117.9022693) @2015-02-03 23:36:14+0900
@tsinychong (@ Tawau, Sabah, East Malaysia): @hztttao____ #GetWellSoonTao 孩子,我们都知道你有多幺的努力工作,但是健康更重要啊!真的心疼你们!Please take care your health carefully boy! Love you all
---
Ulu Kelang, Malaysia (3.1958138, 101.7770204) @ 2015-02-03 23:36:27 +0900
@ayieshcasanova(@): I love you so much-sent to myself
Kau pehal-reply back to myself
Sebabakusayang diri sendiri lakau masih hideup sampai skrg.Kgila
---
Quixeramobim, Brasil (0.0, 0.0) @2015-02-03 23:36:27 +0900
@jackinhanj (@Quixeramobim/ce): A Tuesday with much love that clip♥ #FourFiveSecondsOnVOVO @rihana
---
Quilpué, Chile (-33.0484477, -71.4708018) @2015-02-03 23:37:03 +0900
@PereiraCote(@Quilpué-Chile): #HappyBDayJustinTimberlake i love you!!!: '3 #Mirrors microcancefavorita deel:)
---
lele-de-France, France (0.0, 0.0) @2015-02-03 23:38:11 +0900
@allxflouis(@France): @Real_Liam_Payne 
Ur story is the most touching i've never heard
I cry when I remember what you want through
Our Warrior.Love yax1
---
Merkez, Türkiye (0.0, 0.0) @2015-02-03 23:38:12 +0900
@gltenmer(@): you make me happy @justinbieber, please.
FOLLOW ME, PLEASE.
I am TURKISH BELEEBER.
SEEME, PLZ.♥
I LOVE U SOMUCH♥♥ 
x3.078
---
Lecce, Italy (0.0, 0.0) @2015-02-03 23:40:18 +0900
@Cinzia268 (@Collepasso): Love me like you do.
---
Liloy, Republiking Pilipinas (8.1198248, 122.6804241) @ 2015-02-03 23:42:01+0900
@tonetmurcia(@MurciaSpain): like what..while watching Unforgetable Love there's a certain question that kept on my head..jeez I feel you Nina
---
Shanghai, People's Republic of China (31.21431856, 121.55950506) @2015-02-03 23:43:54 +0900
@lilannash(@Shanghai): #pureandwhole spring new dishes: I already love all of them. This is my favorite place after my...http://t.co/jKD9ndRfqW
---
Los Angeles, United States (0.0, 0.0) @2015-02-03 23:45:16 + 0900
@awarde(@):@chankpc @CNM_JLin_Vids i love how the NY media fundamentally said that we know that hands have been taken with the Lakers
---


if geocode is not specified https://api.twitter.com/1.1/search/tweets.json?q=love&count=100&since_id=(since_id)

if geocode is specified https://api.twitter.com/1.1/search/tweets.json?q=love&geocode=40.7033121,-73.979681,10km&count=100&since_id=(since_id)
I think it will be the same as (since_id) with a tweet id.

Also, as you can see from the example execution results, there are many tweets with a background of (0.0, 0.0). Please note that even tweets containing cities in location information may be missing from the search results if geocode criteria are included.

It was slightly different.

Geolocalization: ... When conducting geo searches, the search API will first attempt to find tweets which have lat/long within the queried geocode, and in case of not having success, it will attempt to find tweets created by users whose profile location can be reverse geocoded into a lat/long within the queried geocode, meaning that is possible to receive tweets which do not include lat/long information.
The Search API|Twitter Developers

It seems that geocode searches also use Profile location information.


2022-09-30 18:34

I haven't checked the operation, so it might be wrong, but
Why don't you search users/search and check the geo attribute of the tweet?


2022-09-30 18:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.