python - Calculating speed using public GPS data -
i'm scraping web api displays latitude , longitude of bus.
the web-service doesn't seems have fixed update time gps position, can take 1 second 30 seconds.
when update takes long reasonable speeds (10km/h~80km/h), when update happens in less 10 seconds, unreal speeds, 1000 km/h.
def haversine(lon1, lat1, lon2, lat2): """calculate distance between 2 points""" lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 = 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 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 = {} requests.session() s: while true: response = s.get(url) t = time.time() content = json.loads(response.content) 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 , update_time: print "bus {bus_prefix} traveling @ {speed}\t" \ "last update in: {update_time}".format(**locals()) buses[bus_prefix] = latitude, longitude, t time.sleep(1)
maybe i'm doing math wrong, or buses in city racing, double checked everything, including racing!
here's debug did try figure out what's going on:
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 traveling @ 687.2 km/h last update in: 00:01
can spot mistake? or right approach? haversine right tool job?
from posted url
, got follwoing output:
[{"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}]
this list of dictionaries, assume each dictionary referring 1 bus,
in each dictionary, there key
called ts
, should time stamp each updated lat
, long
, it's corresponding value
should used calculations speed
give more accurate results:
t = bus["ts"]
Comments
Post a Comment