if语句检查坐标是否在一个范围内

时间:2013-09-26 09:07:52

标签: python if-statement twitter geo tweepy

以下是我试图传输推文的项目代码的一部分,我计划将其保存到Google App Engine的数据库中。对我来说,能够获得坐标的纬度和长值非常重要。 (我打算稍后绘制这些。)

目前的结果看起来像这样......

'推文文字'@删除不确定,说实话......作为谷歌产品,你会这么认为。他们可能在网上商店有官方扩展。 \'用户名'已被删除 \'创建于'2013-09-26 08:39:45 \'使用forTwitter for Android创建 \'geo't {u'type':u'Point',u'coordinates':[52.569001,-2.7846582]} \'coordinates't {u'type':u'Point',u'coordinates':[ -2.7846582,52.569001]}

我喜欢做的是改变它所说的“如果status.coordinates不是None”来检查坐标是否在一个范围内。即Lat 50 - 55和long 0 - 5.

谢谢! :)

class CustomStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        if status.coordinates is not None:
            try:
                print "'tweet text'%s\n\ 'User Name't%s\n\  'Created at't%s\n\  'Created with't%s\n\ 'geo't%s\ 'coordinates't%s" % (status.text, 
                                  status.author.screen_name, 
                                  status.created_at, 
                                  status.source,
                                  status.geo,
                                  status.coordinates)
            except Exception, e:
                print >> sys.stderr, 'Encountered Exception:', e
                pass

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

4 个答案:

答案 0 :(得分:1)

您可能希望根据地球上两点的great-circle distance来决定:

from math import *

def great_circle_distance(coordinates1, coordinates2):
  latitude1, longitude1 = coordinates1
  latitude2, longitude2 = coordinates2
  d = pi / 180  # factor to convert degrees to radians
  return acos(sin(longitude1*d) * sin(longitude2*d) +
              cos(longitude1*d) * cos(longitude2*d) *
              cos((latitude1 - latitude2) * d)) / d

def in_range(coordinates1, coordinates2, range):
  return great_circle_distance(coordinates1, coordinates2) < range

请记住,地球的90度代表传统的10000公里(AFAIK是仪表的古老定义),因此要获得10公里的半径,只需使用0.09度。

答案 1 :(得分:0)

假设坐标以[纬度,经度]格式给出,您可以按如下方式检查:

def check_coords(coords):
    lat = coords[0]
    lng = coords[1]
    return 50 < lat < 55 and 0 < lng < 55

如果纬度介于50 - 55之间且经度介于0 - 5之间,则返回True。如果其中一个超出其定义的范围,则该函数将返回False

编辑:将它添加到您的班级将使它看起来像这样:

class CustomStreamListener(tweepy.StreamListener):

    def on_status(self, status):

        if status.coordinates is not None:
            # coordinates_in_range will be either True or False
            coordinates_in_range = self.check_coords(status.coordinates['coordinates'])
            try:
                print "'tweet text'%s\n\ 'User Name't%s\n\  'Created at't%s\n\  'Created with't%s\n\ 'geo't%s\ 'coordinates't%s" % (status.text, 
                                  status.author.screen_name, 
                                  status.created_at, 
                                  status.source,
                                  status.geo,
                                  status.coordinates)
            except Exception, e:
                print >> sys.stderr, 'Encountered Exception:', e
                pass

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

    def check_coords(self, coords):
        latitude, longitude = coords
        return 50 < latitude < 55 and 0 < longitude < 55

答案 2 :(得分:0)

感谢@Alfe和@Hellsgate的帮助和建议。

以下代码有效(目前Hellsgate上面的代码返回地理标记的推文但不按坐标过滤。)

在CustomStreamListener之上,您只需添加import语句和OAuth方法。以下代码仅返回英国各地的推文,搜索条件为“Rarity Diamonds,Applejack,Discord”

class CustomStreamListener(tweepy.StreamListener):

def check_coords(self, status):
    if status.coordinates is not None:
        lat = status.coordinates['coordinates'][1]
        lng = status.coordinates['coordinates'][0]        
        return 49.7 < lat < 58.5 and -6 < lng < 2.1

def on_status(self, status):


    if self.check_coords(status):
        # if check_coords returns true, the following will run
        try:
            print "'tweet text'%s\n\ 'User Name't%s\n\  'Created at't%s\n\  'Created with't%s\n\ 'geo't%s\ 'coordinates't%s" % (status.text, 
                              status.author.screen_name, 
                              status.created_at, 
                              status.source,
                              status.geo,
                              status.coordinates)
        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e
            pass

def on_error(self, status_code):
    print >> sys.stderr, 'Encountered error with status code:', status_code
    return True # Don't kill the stream

def on_timeout(self):
    print >> sys.stderr, 'Timeout...'
    return True # Don't kill the stream


streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60)


print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),)
"""For track=[""], put in words to search for. Commas separate individual terms IE"Applejack, Discord",
to search for tweets containing more than one term, separate keywords with a space. IE "Rarity Diamonds" """
streaming_api.filter(follow=None, track=["Rarity Diamonds,Applejack,Discord"])

答案 3 :(得分:0)

def getDistance(point, point2):
    xdis = abs(point[0] - point2[0])
    ydis = abs(point[1] - point2[1])
    return (ydis**2 + xdis**2)**0.5

if getDistance([0,0],[4,4]) < 5:
    print("Point with x=4 and y=4 is in range of 0,0")