def test_basic(self): point = GeoPoint(1.1234, 45.983) radPoint = point.degree2radian() self.assertAlmostEqual(radPoint.lon, 0.0196070288, places=4, msg=None, delta=None) self.assertAlmostEqual(radPoint.lat, 0.80255475, places=4, msg=None, delta=None) degPoint = radPoint.radian2degree() self.assertAlmostEqual(degPoint.lon, point.lon, places=4, msg=None, delta=None) self.assertAlmostEqual(degPoint.lat, point.lat, places=4, msg=None, delta=None)
def process_graph_hopper_reply(gh_json): if 'paths' not in gh_json: if 'message' in gh_json: raise Exception('error in gh query: %s' % gh_json['message']) else: raise Exception('Badly formatted json %s' % gh_json) path = gh_json['paths'][0] length = round(path['distance']) points = [GeoPoint(p[1], p[0]) for p in path['points']['coordinates']] return length, points
def fetch(): response = api.GET( endpoint='http://api.openweathermap.org/data/2.5/onecall', APPID=os.environ["WEATHER_KEY"], **dict(gp.fetch()), units='imperial').json() # open cache file for writing and dump to cache CACHE.save('weather.json', response) # return the response in case we still want it return response
def process_google_maps_reply(google_json): if google_json['status'] != 'OK': raise Exception('status is not OK, status=%s, json=%s' % (google_json['status'], google_json)) route = google_json['routes'][0] leg = route['legs'][0] route_length = round(leg['distance']['value']) # encoded_polyline = route['overview_polyline']['points'] points_dicts = [leg["start_location"] ] + [step["end_location"] for step in leg["steps"]] points = [GeoPoint(p['lat'], p['lng']) for p in points_dicts] return route_length, points
def bounds_command(bot, update): msg_text = update.message.text.strip() ndx = msg_text.find(' ') if ndx == -1: send_message(bot, update, "incorrect") else: arr = msg_text[ndx + 1:].split(',') if len(arr) != 5: send_message(bot, update, "incorrect: " + repr(length(arr)) + "parts") else: p1 = GeoPoint(float(arr[1]), float(arr[0])) p2 = GeoPoint(float(arr[3]), float(arr[2])) offset = int(arr[4]) zone = GeoZone(p1, p2, offset) bot.sendLocation(chat_id=update.message.chat_id, longitude=zone.central.lon, latitude=zone.central.lat) db = DBHelper() res = db.get_zone(zone.bounds) send_message(bot, update, repr(zone.radius) + "\n" + res)
def test_central(self): wrapper = GeoWrapper() p1 = GeoPoint(43.978471, 56.319519) p2 = GeoPoint(43.977447, 56.319724) c = wrapper.central(p1, p2) self.assertAlmostEqual(wrapper.distance(p1, c) / 100., wrapper.distance(p2, c) / 100., places=2, msg=None, delta=None) bounds = wrapper.bounds(c, 30) print(wrapper.distance(c, GeoPoint(c.lon, bounds['minLat']))) print(wrapper.distance(c, GeoPoint(c.lon, bounds['maxLat']))) print(wrapper.distance(c, GeoPoint(bounds['minLon'], c.lat))) print(wrapper.distance(c, GeoPoint(bounds['maxLon'], c.lat)))
def test_distance(self): wrapper = GeoWrapper() self.assertAlmostEqual(wrapper.distance(GeoPoint( -139.398, 77.1539), GeoPoint(-139.55, -77.1804)) / 100., 171660.29, places=2, msg=None, delta=None) self.assertAlmostEqual(wrapper.distance(GeoPoint( 120.398, 77.1539), GeoPoint(129.55, 77.1804)) / 100., 2258.83, places=2, msg=None, delta=None) self.assertAlmostEqual(wrapper.distance(GeoPoint( -120.398, 77.1539), GeoPoint(129.55, 77.1804)) / 100., 23326.69, places=2, msg=None, delta=None)
def build_walking_distance_table(stops_file, stations_file, output_file, google_api_key, gh_api_key, max_distance=400, simulate=False): def format_path(list_of_points): return ' '.join('%f %f' % (p.lat, p.long) for p in list_of_points) # read stops data table = [] with open(stops_file, "r", encoding='utf8') as f: reader = csv.DictReader(f) for data in reader: data['station_distance'] = float(data['train_station_distance']) if data['stop_code'] != data['nearest_train_station'] and int( data['train_station_distance']) <= max_distance: data['stop_point'] = GeoPoint(data['stop_lat'], data['stop_lon']) table.append(data) print("Read %d stops with straight_line distance <= %d" % (len(table), max_distance)) # getting real coordinates for train stations station_real_location = defaultdict(lambda: []) with open(stations_file, "r", buffering=-1, encoding="utf8") as g: reader = csv.DictReader(g) for line in reader: if line['exit_only'] == 'False': # we skip exits for now because they make things to complicated station_real_location[line['stop_code']].append( GeoPoint(float(line['exit_lat']), float(line['exit_lon']))) print("Read locations for %d train stations" % len(station_real_location)) print("Stations with 1 entrance: %d" % len([l for l in station_real_location.values() if len(l) == 1])) print("Stations with 2 entrances: %d" % len([l for l in station_real_location.values() if len(l) == 2])) print("Stations more than 2 entrances: %d" % len([l for l in station_real_location.values() if len(l) > 2])) queries_required = sum( len(station_real_location[stop['nearest_train_station']]) for stop in table) print("Total number of queries required=%d" % queries_required) if simulate: return # create station_walking_distance table headers = [ 'bus_stop_code', 'bus_stop_lat', 'bus_stop_lon', 'train_station_code', 'train_station_entrace_id', 'train_station_lat', 'train_station_lon', 'distance_in_meters', 'distance_source', 'distance_calcated_on', 'notes' ] with open(output_file, 'w', newline='', encoding='utf8') as f: writer = csv.DictWriter(f, fieldnames=headers, lineterminator='\n', extrasaction='ignore') writer.writeheader() for stop in table: # change fields names to station_walking_distance names stop['bus_stop_code'] = stop['stop_code'] stop['bus_stop_lat'] = stop['stop_lat'] stop['bus_stop_lon'] = stop['stop_lon'] stop['train_station_code'] = stop['nearest_train_station'] stop['distance_calcated_on'] = datetime.datetime.now().strftime( "%d/%m/%Y") # calculate with Google stop['distance_source'] = 'Google' # a station may have multiple entrances for point in station_real_location[stop['nearest_train_station']]: stop['train_station_lat'], stop[ 'train_station_lon'] = point.lat, point.long distance, points = google(stop['stop_point'], point, google_api_key) if distance < stop.get('distance_in_meters', 999999): stop['distance_in_meters'] = distance stop['notes'] = format_path(points) writer.writerow(stop) # calculate with Graphopper stop['distance_source'] = 'Graphopper' for point in station_real_location[stop['nearest_train_station']]: stop['train_station_lat'], stop[ 'train_station_lon'] = point.lat, point.long distance, points = gh(stop['stop_point'], point, gh_api_key) if distance < stop.get('distance_in_meters', 999999): stop['distance_in_meters'] = distance stop['notes'] = format_path(points) writer.writerow(stop) f.flush()
from folium import Map, Marker, Popup from geo import GeoPoint #todo: 1. add the real other point of the correct point. # 2. the user add the point he wants # Get input values locations = [[31.78, 35.04], [41, -1], [36, 17]] # Foliom Map mymap = Map(location=[31.78, 35.04]) for lat, lon in locations: # Create a GeoPoint geopoint = GeoPoint(latitude=lat, longitude=lon) forecast = geopoint.get_weather() popup_content = f""" {forecast[0][0][-8:-6]}h: {round(forecast[0][1])}*f <img src="http://openweathermap.org/img/wn/{forecast[0][-1]}@2x.png" width=35> <hr style="margin:1px"> {forecast[1][0][-8:-6]}h: {round(forecast[1][1])}*f <img src="http://openweathermap.org/img/wn/{forecast[1][-1]}@2x.png" width=35> <hr style="margin:1px"> {forecast[2][0][-8:-6]}h: {round(forecast[2][1])}*f <img src="http://openweathermap.org/img/wn/{forecast[2][-1]}@2x.png" width=35> <hr style="margin:1px"> {forecast[3][0][-8:-6]}h: {round(forecast[3][1])}*f <img src="http://openweathermap.org/img/wn/{forecast[3][-1]}@2x.png" width=35> """ popup = Popup(popup_content, max_width=400) popup.add_to(geopoint) geopoint.add_to(mymap)
def stops_distance(g, stop_id1, stop_id2): """Returns the geographical distance (in meters) between the two stops""" p1 = GeoPoint(g.stops[stop_id1].stop_lat, g.stops[stop_id1].stop_lon) p2 = GeoPoint(g.stops[stop_id2].stop_lat, g.stops[stop_id2].stop_lon) return p1.distance_to(p2)
from pathlib import Path from folium import Map from geo import GeoPoint, GeoMarker LOCATIONS = [[41, -1], [40, 2], [50, 113], [-20, -70]] POPUP = str(Path.cwd() / 'popup.html') MAP = Map() for lat, lon in LOCATIONS: geo = GeoPoint(lat, lon) marker = GeoMarker(geo, POPUP) marker.mark(MAP) MAP.save('map.html')