def main(): r = s2sphere.RegionCoverer() p1 = s2sphere.LatLng.from_degrees(48.831776, 2.222639) p2 = s2sphere.LatLng.from_degrees(48.902839, 2.406) cell_ids = r.get_covering(s2sphere.LatLngRect.from_point_pair(p1, p2)) # print(cell_ids) # create a map map_osm = folium.Map(location=[48.86, 2.3], zoom_start=12, tiles='Stamen Toner') # # get vertices from rect to draw them on map # rect_vertices = [] # for i in [0, 1, 2, 3, 0]: # rect_vertices.append([vertex.lat().degrees(), vertex.lng().degrees()]) # draw the cells style_function = lambda x: {'weight': 1, 'fillColor': '#eea500'} for cellid in cell_ids: cell = s2sphere.Cell(cellid) vertices = [] for i in range(0, 4): vertex = cell.get_vertex(i) latlng = s2sphere.LatLng.from_point(vertex) # currently the angle is in radians vertices.append((math.degrees(latlng.lat().radians), math.degrees(latlng.lng().radians))) gj = folium.GeoJson({"type": "Polygon", "coordinates": [vertices]}, style_function=style_function) gj.add_child(folium.Popup(cellid.to_token())) gj.add_to(map_osm)
def coords_of_cell(cell_id): cell = s2sphere.Cell(s2sphere.CellId(int(cell_id))) coords = [] for value in range(0, 4): vertex = s2sphere.LatLng.from_point(cell.get_vertex(value)) coords.append([vertex.lat().degrees, vertex.lng().degrees]) return coords
def get_cell_from_string(str_id): raw_id = long(str_id) if raw_id < 0: # overflow cell_id = s2sphere.CellId(raw_id) return s2sphere.Cell.from_face_pos_level(cell_id.face(), cell_id.pos(), 10) else: return s2sphere.Cell(s2sphere.CellId(raw_id))
def get_s2_coverage(swLat, swLng, neLat, neLng): geoms = [] r = s2sphere.RegionCoverer() r.min_level = 10 r.max_level = 10 r.max_cells = 40 p1 = s2sphere.LatLng.from_degrees(float(swLat), float(swLng)) p2 = s2sphere.LatLng.from_degrees(float(neLat), float(neLng)) covering = r.get_covering(s2sphere.LatLngRect.from_point_pair(p1, p2)) for cell_id in covering: cell_to_render = {} rect_bound = s2sphere.Cell(cell_id) center = s2sphere.LatLng.from_point(rect_bound.get_center()) cell_to_render['s2_cell_id'] = str(cell_id.id()) cell_to_render['center'] = { 'lat': center.lat().degrees, 'lng': center.lng().degrees } cell_to_render['vertices'] = get_vertices_from_s2cell(rect_bound) # log.info(rect_bound.approx_area()) del rect_bound geoms.append(cell_to_render) return geoms
def get_weather(): with session_scope() as session: weathers = session.query(Weather) markers = [] for weather in weathers: cell = s2sphere.Cell( s2sphere.CellId(weather.s2_cell_id).parent(10)) center = s2sphere.LatLng.from_point(cell.get_center()) converted_s2_cell_id = s2sphere.CellId.from_lat_lng( s2sphere.LatLng.from_degrees(center.lat().degrees, center.lng().degrees)).parent(10) markers.append({ 'id': 'weather-' + str(weather.id), 'coords': [(get_vertex(cell, v)) for v in range(0, 4)], 'center': (center.lat().degrees, center.lng().degrees), 'condition': weather.condition, 'alert_severity': weather.alert_severity, 'warn': weather.warn, 'day': weather.day, 's2_cell_id': converted_s2_cell_id.id() }) return markers
def __init__(self, queries, lat, lon, level): """ I copied most of this code from Map-A-Droid. """ ll = s2sphere.LatLng.from_degrees(lat, lon) cell = s2sphere.CellId().from_lat_lng(ll) cellId = cell.parent(level).id() cell = s2sphere.Cell(s2sphere.CellId(cellId)) path = [] for v in range(0, 4): vertex = s2sphere.LatLng.from_point(cell.get_vertex(v)) path.append([vertex.lat().degrees, vertex.lng().degrees]) mb_path = [] for v in range(0, 4): vertex = s2sphere.LatLng.from_point(cell.get_vertex(v)) mb_path.append([vertex.lng().degrees, vertex.lat().degrees]) mb_path.append(mb_path[0]) stringfence = "" for coordinates in path: stringfence = f"{stringfence}{coordinates[0]} {coordinates[1]}," stringfence = f"{stringfence}{path[0][0]} {path[0][1]}" count = queries.count_in_cell(stringfence) self.path = path self.mapbox_path = mb_path self.stops = count[0] + count[1] self.portals = count[2]
def plotFootprint(sat): angle = calcCapAngle(sat.elevation.km, 35) cells = get_cell_ids(sat.latitude.degrees, sat.longitude.degrees, angle) print(len(cells)) proj = cimgt.Stamen('terrain-background') plt.figure(figsize=(6,6), dpi=400) ax = plt.axes(projection=proj.crs) ax.add_image(proj, 6) # ax.coastlines() ax.set_extent([sat.longitude.degrees-10., sat.longitude.degrees+10., sat.latitude.degrees-10, sat.latitude.degrees+10.], crs=ccrs.Geodetic()) ax.background_patch.set_visible(False) geoms = [] for cellid in cells: new_cell = s2sphere.Cell(cellid) vertices = [] for i in range(0, 4): vertex = new_cell.get_vertex(i) latlng = s2sphere.LatLng.from_point(vertex) vertices.append((latlng.lng().degrees, latlng.lat().degrees)) geo = Polygon(vertices) geoms.append(geo) ax.add_geometries(geoms, crs=ccrs.Geodetic(), facecolor='red', edgecolor='black', alpha=0.4) ax.plot(sat.longitude.degrees, sat.latitude.degrees, marker='o', color='red', markersize=4, alpha=0.7, transform=ccrs.Geodetic()) plt.savefig('test.png')
def cell_id_to_json(cellid_l): cellid = s2sphere.CellId(cellid_l) cell = s2sphere.Cell(cellid) def get_vertex(v): vertex = s2sphere.LatLng.from_point(cell.get_vertex(v)) return { 'lat': vertex.lat().degrees, 'lng': vertex.lng().degrees } shape = [get_vertex(v) for v in range(0, 4)] return { 'id': str(cellid.id()), 'id_signed': cellid.id(), 'token': cellid.to_token(), 'pos': cellid.pos(), 'face': cellid.face(), 'level': cellid.level(), 'll': { 'lat': cellid.to_lat_lng().lat().degrees, 'lng': cellid.to_lat_lng().lng().degrees }, 'shape': shape }
def check_children(parent): for parent, kid in self.edges(parent): if self.is_link(kid): closest_links_to_cell.append(kid) elif neighbourhood_of_g_node.may_intersect( s2.Cell(s2.CellId(kid))): check_children(kid)
def process_weather(self, json_data): self.weather_total += 1 if args.no_weather: return to_keep = [ "s2_cell_id", "latitude", "longitude", "cloud_level", "rain_level", "snow_level", "fog_level", "wind_direction", "gameplay_weather", "severity", "warn_weather", "world_time", "last_updated" ] weather = {} # This is for mon alt's fork. It's almost RM, but not quite. # As if this writing, RM doesn't have support for weather # 02/28/18 if 'coords' in json_data: id = json_data['s2_cell_id'] weather[id] = json_data wh_weather = weather[id].copy() # Map all the fields weather[id]['severity'] = json_data['alert_severity'] weather[id]['last_updated'] = time.gmtime( json_data['time_changed']) weather[id]['warn_weather'] = json_data['warn'] # Day =1 night = 2 weather[id]['world_time'] = json_data['day'] # condition weather[id]['gameplay_weather'] = json_data['condition'] # Mon alt sends the coordinates, but we do not actually need them. cell_id = s2sphere.CellId(long(id)) cell = s2sphere.Cell(cell_id) center = s2sphere.LatLng.from_point(cell.get_center()) weather[id]['latitude'] = center.lat().degrees weather[id]['longitude'] = center.lng().degrees # This is a WAG until I get more info weather[id]['cloud_level'] = 0 weather[id]['rain_level'] = 0 weather[id]['snow_level'] = 0 weather[id]['fog_level'] = 0 weather[id]['wind_direction'] = 0 # And this is stock RM else: pass # copies all the keys we want for the DB weather[id] = { key: weather[id][key] for key in weather[id] if key in to_keep } log.debug("%s", weather) # put it into the db queue db_queue.put((Weather, weather)) if args.webhooks: wh_queue.put(('weather', wh_weather))
def _get_degrees_vertex(cell: s2.CellId) -> List[Tuple[int, int]]: a = [] for i in range(4): v = s2.Cell(cell).get_vertex_raw(i) s = s2.LatLng.from_point(v) a.append((s.lng().degrees, s.lat().degrees)) return a
def s2_latlng_to_polygon(latlng,parent_level=7): cell = s2sphere.Cell.from_lat_lng(s2sphere.LatLng.from_degrees(*latlng)) parent_cell = s2sphere.Cell(cell.id().parent(parent_level)) polygon_tuples = [ (float(x[1]),float(x[0])) for x in [ str(s2sphere.LatLng.from_point(parent_cell.get_vertex(k))).replace('LatLng: ','').split(',') for k in range(4) ] ] return polygon_tuples
def _hexid2latlng(self, hexid): # convert hexid to latlng of cellcenter cellid = s2.CellId().from_token(hexid) cell = s2.Cell(cellid) point = cell.get_center() latlng = s2.LatLng(0, 0).from_point(point).__repr__() _, latlng = latlng.split(' ', 1) lat, lng = latlng.split(',', 1) lat = float(lat) lng = float(lng) return lat, lng
def get_feature(self, s): c = s2sphere.Cell(s2sphere.CellId(s)) y = [ s2sphere.LatLng.from_point(c.get_vertex(i)) for i in [0, 1, 2, 3, 0] ] x = [[(x.lng().degrees, x.lat().degrees) for x in y]] g = geojson.Polygon(x) f = geojson.Feature(geometry=g, properties={ 's2id': str(s), 'lvl': str(c.level()) }) return f
def get_s2_cells(n=north, w=west, s=south, e=east, level=12): region_covered = s2sphere.LatLngRect.from_point_pair( s2sphere.LatLng.from_degrees(n, w), s2sphere.LatLng.from_degrees(s, e)) coverer = s2sphere.RegionCoverer() coverer.min_level = level coverer.max_level = level coverer.max_cells = 50 covering = coverer.get_covering(region_covered) markers = [] for cellid in covering: cell = s2sphere.Cell(cellid) markers.append({ 'id': 'cell-' + str(cellid.id()), 'coords': [(get_vertex(cell, v)) for v in range(0, 4)] }) return markers
def generate_cells(nLat, nLng, sLat, sLng, cell_size=13): points = [] area = s2sphere.LatLngRect.from_point_pair( s2sphere.LatLng.from_degrees(nLat, nLng), s2sphere.LatLng.from_degrees(sLat, sLng)) r = s2sphere.RegionCoverer() r.min_level = cell_size r.max_level = cell_size cells = r.get_covering(area) for cell in cells: c = s2sphere.Cell(cell.parent(13)) ll = s2sphere.LatLng.from_point(c.get_center()) points.append([ll.lat().degrees, ll.lng().degrees]) return points
def getCircleCoveringRect(lat, lng, radius, parent_level): radius_radians = earthMetersToRadians(radius) latlng = s2sphere.LatLng.from_degrees(float(lat), float(lng)).normalized().to_point() region = s2sphere.Cap.from_axis_height( latlng, (radius_radians * radius_radians) / 2) coverer = s2sphere.RegionCoverer() coverer.min_level = int(parent_level) coverer.max_level = int(parent_level) coverer.max_cells = MAX_S2_CELLS covering = coverer.get_covering(region) s2_rect = [] for cell_id in covering: new_cell = s2sphere.Cell(cell_id) vertices = [] for i in range(4): vertex = new_cell.get_vertex(i) latlng = s2sphere.LatLng.from_point(vertex) vertices.append((math.degrees(latlng.lat().radians), math.degrees(latlng.lng().radians))) s2_rect.append(vertices) return s2_rect
def plotFootprint(lat: float, lon: float, cells: List): """Uses cartopy to replot the footprint, mostly used for debugging and validating math and library usage""" proj = cimgt.Stamen('terrain-background') plt.figure(figsize=(6, 6), dpi=400) ax = plt.axes(projection=proj.crs) ax.add_image(proj, 6) ax.set_extent([lon - 10., lon + 10., lat - 10, lat + 10.], crs=ccrs.Geodetic()) ax.background_patch.set_visible(False) geoms = [] for cellid in cells: new_cell = s2sphere.Cell(cellid) vertices = [] for i in range(0, 4): vertex = new_cell.get_vertex(i) latlng = s2sphere.LatLng.from_point(vertex) vertices.append((latlng.lng().degrees, latlng.lat().degrees)) geo = Polygon(vertices) geoms.append(geo) ax.add_geometries(geoms, crs=ccrs.Geodetic(), facecolor='red', edgecolor='black', alpha=0.4) ax.plot(lon, lat, marker='o', color='red', markersize=4, alpha=0.7, transform=ccrs.Geodetic()) plt.savefig('test.png')
#for stepy in range(0,steps_lo+1) ] #for stepx in range(0,steps_lo+1) ] #grid_gps_flat_lo = [ a for b in grid_gps_lo for a in b ] #grid_gps_flat_lo = [] grid_gps_flat_lo = grid_gps_flat #################### if args.s2file: print(' getting mesh gps coords') with open(args.s2file,'rb') as f: import pickle import s2sphere s2cells=pickle.load(f) gps_coords=[] for cellid in s2cells: cell=s2sphere.Cell(cellid) latlng=cellid.to_lat_lng() lat=latlng.lat().degrees lng=latlng.lng().degrees x,y = map.to_pixels(lat,lng) if (((x>=px0 and x<=px2) or (x>=px2 and x<= px0)) and ((y>=px1 and y<=px3) or (y>=px3 and y<= px1))): gps_coords.append([lat,lng]) print(' len=',len(gps_coords)) else: gps_coords=[] ######################################## #plot gps grid if args.plot_sample_points:
def get_s2_cell_as_polygon(self, lat, lon, level=12): cell = s2sphere.Cell(s2sphere.CellId.from_lat_lng(s2sphere.LatLng.from_degrees(lat, lon)).parent(level)) return [(self.get_vertex(cell, v)) for v in range(0, 4)]
def get_cell_level(cell_id): return s2sphere.Cell(s2sphere.CellId(cell_id)).level()
def test_average_area(self): # has not equivalent SWIG wrapped version py_cell = s2sphere.Cell(s2sphere.CellId.from_token('89c259c4')) self.assertEqual(py_cell.average_area(), 3.120891902436607e-08)