我正在抓取显示公交车纬度和经度的网络API。
网络服务似乎没有固定的GPS位置更新时间,可能需要1秒到30秒。
当更新需要很长时间我得到合理的速度(10km / h~80km / h),但是当更新发生在不到10秒的时间内时,我会得到不真实的速度,最高可达1000 km / h。
def haversine(lon1, lat1, lon2, lat2):
"""Calculate the distance between two points"""
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def get_speed(new_lat, new_lng, cur_time):
old_lat, old_lng, old_time = buses[bus_prefix]
if (new_lat, new_lng) != (old_lat, old_lng):
distance = haversine(old_lng, old_lat, new_lng, new_lat)
speed = distance / (cur_time - old_time) * 3600
_speed = "%.1f km/h" % speed
updated_time = "%02d:%02d"%(divmod(cur_time-old_time, 60))
return _speed, updated_time
return None, None
url = 'http://api.plataforma.cittati.com.br/m3p/js/vehicles/service/22233'
buses = {}
with requests.session() as s:
while True:
response = s.get(url)
t = time.time()
content = json.loads(response.content)
for bus in content:
bus_prefix = bus['prefix']
latitude = bus['lat']
longitude = bus['lng']
if bus_prefix in buses:
speed, update_time = get_speed(latitude, longitude, t)
if speed and update_time:
print "Bus {bus_prefix} is traveling at {speed}\t" \
"Last update in: {update_time}".format(**locals())
buses[bus_prefix] = latitude, longitude, t
time.sleep(1)
也许我做错了数学,或者我所在城市的公共汽车都在比赛,但我仔细检查了一切,包括比赛!
这是我做过的一项调试,试图找出正在发生的事情:
old_lat = -32.0916777778
new_lat = -32.0937277778
new_lng = -52.1608333333
old_lng = -52.1598611111
distance = 0.245660526035 in kms
old_time = 1436580324.66 in epoch seconds
cur_time = 1436580325.94 in epoch seconds
delta time = 1.28700017929 in seconds
speed = 687.162214861 in km/h
Bus 1145 is traveling at 687.2 km/h Last update in: 00:01
有人能发现任何错误吗?或者这是正确的方法吗? Haversine是否适合这项工作?
答案 0 :(得分:2)
从您发布的url
,我得到了以下输出:
[{"plate":"IUZ4600","prefix":"1310","ts":1436583122000,"lat":-32.061505555555556,"lng":-52.147172222222224,"bearing":37},{"plate":"ISO8600","prefix":"1145","ts":1436583099000,"lat":-32.15838333333333,"lng":-52.19098888888889,"bearing":309}]
这是一个词典列表,我假设每个词典都指的是一个总线,
在每个字典中,有一个名为key
的{{1}},它应该是每个更新的ts
和lat
的时间戳,它是相应的long
应该用于value
的计算,以便为您提供更准确的结果:
speed
答案 1 :(得分:0)
可能的问题是,由于gps不是非常精确,如果测量1和测量2在相反的方向上都偏离了100米,那么这是另外200米的距离。时间越长,差异越小影响结果。我想说最好的解决方案是只进行超过15秒左右的更新,从而最大限度地减少错误。