def test_strip_srid(self): """ strip SRID """ geom1 = Geometry("010100000000000000000000000000000000000000") geom2 = Geometry("0101000020E610000000000000000000000000000000000000") self.assertIsNone(geom1.srid) self.assertEquals(geom2.srid, 4326) geom2.srid = None self.assertIsNone(geom2.srid) self.assertEquals(geom1.wkb, geom2.wkb) geom2.srid = None self.assertIsNone(geom2.srid) self.assertEquals(geom1.wkb, geom2.wkb)
def _get_predicates(self, quals): query = None bounds = None for qual in quals: if qual.field_name == 'query' and qual.operator == '=': query = qual.value if qual.field_name == 'geom' and qual.operator in ['&&', '@']: # note A ~ B is transformed into B @ A shape = Geometry(qual.value).shapely bounds = shape.bounds elif qual.value == 'geom' and qual.operator == '&&': shape = Geometry(qual.field_name).shapely bounds = shape.bounds return query, bounds
def containsPoint(request): #위험 지역 우회 global gu_coordinate pointlist = [] line = "" line_point = [] count = 0 gu_bound = Female2.objects.filter(female2_crime_type="구경계", gu="양천구").get() gis = Geometry(gu_bound.female2_crime_loc.hex()[8:]) gi = shape(gis) if request.method == "POST": pistes = request.POST.get('draw') pist = pistes.split(",") for p in pist: if (pist.index(p) % 2 == 0): x = p y = pist[pist.index(p) + 1] point = Point(float(y), float(x)) pointlist.append(point) linear = LineString(pointlist).buffer(0.003) for multi in global_contain_coordinate: if linear.contains(multi): linear = linear.difference(multi.buffer(0.0)) if linear.intersection(gi).geom_type == 'Polygon': line += "_" + str(linear.centroid.x) + "," + str(linear.centroid.y) else: for l in list(linear.intersection(gi)): line += "_" + str(l.centroid.x) + "," + str(l.centroid.y) return HttpResponse(json.dumps({'p': line[1:]}), content_type="application/json")
def test_read_wkb_point_big_endian(self): """ read WKB Point """ geom = Geometry("000000000140000000000000004010000000000000") self.assertIsInstance(geom, Point) self.assertEqual((2, 4, None), (geom.x, geom.y, geom.z))
def donglevel(request): map = folium.Map(location=[37.5518838, 126.9858763], zoom_start=12) dongm = DongLevel.objects.values('dong_level_tot', 'dong_nm') dong_df = pd.DataFrame(dongm) dongloc = DongLevel.objects.all() loc_list = [] for i in dongloc: gis = Geometry(i.dong_loc.hex()[8:]) crime_location = { "type": "Feature", "properties": { "dong_nm": i.dong_nm }, "geometry": gis.geojson } loc_list.append(crime_location) pistes = {"type": "FeatureCollection", "features": loc_list} folium.Choropleth(geo_data=pistes, data=dong_df, columns=('dong_nm', 'dong_level_tot'), fill_color='BuPu', key_on='feature.properties.dong_nm').add_to(map) maps = map._repr_html_() return render(request, 'home.html', {'map': maps})
def showFemale(request): global g global getGu crime_type="" loc_list=[] if request.method=="POST": filter_value=request.POST['female_filter'] crime_type="전체_"+filter_value female_total=Female2.objects.filter(gu=getGu,female2_crime_type=crime_type).all() linear = cmp.LinearColormap( [ 'green','blue','red'], vmin=10, vmax=300) map = folium.Map(location=[37.55582994870823, 126.9726320033982],zoom_start=15) for loc in female_total: gis= Geometry(loc.female2_crime_loc.hex()[8:]) contain_coordinate=shape(gis.geojson) crime_location={"type":"Feature","properties":{'area':math.ceil(round(contain_coordinate.length,5)*100000)},"geometry":gis.geojson} folium.GeoJson(crime_location,style_function=lambda feature: { 'fillColor': linear(feature['properties']['area']), 'color': linear(feature['properties']['area']), 'weight': 1 }).add_to(map) linear.add_to(map) maps=map._repr_html_() return render(request, 'home.html',{'map':maps})
def pathFinder(request): #위험지역 받는 함수 global startX,startY,endX,endY,startGu,endGu gu_list=['종로구','중구','용산구','성동구','광진구', '동대문구','중랑구','성북구','강북구','도봉구', '노원구','은평구','서대문구','마포구','양천구', '강서구','구로구','금천구','영등포구','동작구', '관악구','서초구','강남구','송파구','강동구',] loc_list=[] if request.method=="POST": startPoint=request.POST.get('start') endPoint=request.POST.get('end') startX=request.POST.get('startX') startY=request.POST.get('startY') endX=request.POST.get('endX') endY=request.POST.get('endY') for find_gu in gu_list: if find_gu in startPoint: startGu=find_gu else: pass if find_gu in endPoint: endGu=find_gu else: pass female_start=Female2.objects.filter(female2_crime_type="전체_전체",gu=startGu).all() female_end=Female2.objects.filter(female2_crime_type="전체_전체",gu=endGu).all() female_total=female_start.union(female_end,all=False) for loc in female_total: gis= Geometry(loc.female2_crime_loc.hex()[8:]) contain_coordinate=shape(gis.geojson) crime_location={"type":"Feature","geometry":gis.geojson} loc_list.append(crime_location) pistes = {"type":"FeatureCollection","features":loc_list} return HttpResponse(json.dumps({'result':pistes}),content_type="application/json")
def converterFeature(geometry): g = Geometry(geometry) coord = g.geojson['coordinates'][0][0] saida = [] for c in coord: c.reverse() saida.append(c) return saida
def converterGeometryPolygon(geometry): g = Geometry(geometry) coord = g.geojson['coordinates'] saida = [] for c in coord[0]: c.reverse() saida.append(c) return saida
def aStar(request): global startGu, endGu center = hexgrid.Point((float(startX) + float(endX)) / 2, (float(startY) + float(endY)) / 2) rate = 110.574 / (111.320 * math.cos(37.55582994870823 * math.pi / 180)) grid = hexgrid.Grid(hexgrid.OrientationFlat, center, Point(rate * 0.00015, 0.00015), morton.Morton(2, 32)) sPoint = grid.hex_at(Point(float(startX), float(startY))) ePoint = grid.hex_at(Point(float(endX), float(endY))) map_size = max(abs(sPoint.q), abs(sPoint.r)) road1 = Roadtohexgrid.objects.filter(is_danger=1, hexgrid_gu=startGu).all() road2 = Roadtohexgrid.objects.filter(is_danger=1, hexgrid_gu=endGu).all() total_road = road1.union(road2, all=False) wall1 = Roadtohexgrid.objects.filter(is_danger=0, hexgrid_gu=startGu).all() wall2 = Roadtohexgrid.objects.filter(is_danger=0, hexgrid_gu=endGu).all() total_wall = wall1.union(wall2, all=False) wh = GridWithWeights(layout_flat, Point(rate * 0.00015, 0.00015), center, map_size + 5) for r in total_road: gis = Geometry(r.hexgrid_loc.hex()[8:]) h = grid.hex_at(shape(gis.geojson)) wh.weights[(h.q, h.r)] = 1 for w in total_wall: gis = Geometry(w.hexgrid_loc.hex()[8:]) h = grid.hex_at(shape(gis.geojson)) wh.weights[(h.q, h.r)] = 200 start, goal = (sPoint.q, sPoint.r), (ePoint.q, ePoint.r) came_from, cost_so_far = a_star_search(wh, start, goal) pointList = reconstruct_path(came_from, start=start, goal=goal) plist = [] for p in pointList: point = wh.hex_to_pixel(hexgrid.Hex(p[0], p[1])) plist.append([point.x, point.y]) crime_location = { "type": "Feature", "geometry": { "type": "LineString", "coordinates": plist } } pistes = {"type": "FeatureCollection", "features": [crime_location]} return HttpResponse(json.dumps({'pistes': pistes}), content_type="application/json")
def test_geojson(self): """ fdw.GeoJSON.execute receive GeoJSON response """ options = {'url': self.EXAMPLE} columns = ['geom'] fdw = GeoJSON(options, columns) rows = fdw.execute([], columns) for row in rows: wkb = row["geom"] geom = Geometry(wkb) self.assertIsInstance(geom, Point)
def test_multigeometry_changedimensionality(self): """ change dimensionality of a MultiGeometry """ wkb = wkb_gc geom = Geometry(wkb) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) geom.dimz = True geom.dimm = True self.assertEquals(geom.dimz, True) self.assertEquals(geom.dimm, True) geom.srid = geom.srid # clear cached WKB self.assertNotEquals(geom.__str__().lower(), wkb.lower())
def test_read_ewkb_point_srid(self): """ read EWKB Point,4326 """ wkb = "0101000020E610000000000000000000000000000000000000" geom = Geometry(wkb) self.assertEquals(geom.type, "Point") self.assertEquals(geom.srid, 4326) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) postgis_type = "geometry(Point,4326)" self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals(geom.__repr__(), "<Point: 'geometry(Point,4326)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower())
def test_read_wkb_point(self): """ read WKB Point """ wkb = "010100000000000000000000000000000000000000" geom = Geometry(wkb) self.assertEquals(geom.type, "Point") self.assertIsNone(geom.srid) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) postgis_type = "geometry(Point)" self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals(geom.__repr__(), "<Point: 'geometry(Point)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower())
def test_read_wkb_polygon(self): """ read WKB Polygon """ wkb = wkb_pg geom = Geometry(wkb) self.assertEquals(geom.type, "Polygon") self.assertEquals(geom.srid, None) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) postgis_type = "geometry(Polygon)" self.assertEquals(geom.exterior.type, "LineString") self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals(geom.__repr__(), "<Polygon: 'geometry(Polygon)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower())
def test_read_wkb_linestring(self): """ read WKB LineString """ wkb = wkb_ln geom = Geometry(wkb) self.assertEquals(geom.type, "LineString") self.assertEquals(geom.srid, None) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) postgis_type = "geometry(LineString)" geom.vertices self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals(geom.__repr__(), "<LineString: 'geometry(LineString)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower())
def test_read_wkb_multipolygon(self): """ read WKB MultiPolygon """ wkb = wkb_mpg geom = Geometry(wkb) self.assertEquals(geom.type, "MultiPolygon") self.assertEquals(geom.srid, None) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) postgis_type = "geometry(MultiPolygon)" self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals(geom.__repr__(), "<MultiPolygon: 'geometry(MultiPolygon)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower()) for g in geom.geometries: self.assertEquals(g.type, "Polygon")
def test_read_wkb_multilinestring(self): """ read WKB MultiLineString """ wkb = wkb_mln geom = Geometry(wkb) self.assertEquals(geom.type, "MultiLineString") self.assertEquals(geom.srid, None) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, True) postgis_type = "geometry(MultiLineStringM)" self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals(geom.__repr__(), "<MultiLineString: 'geometry(MultiLineStringM)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower()) for g in geom.geometries: self.assertEquals(g.type, "LineString")
def to_convert_geometry_point(geometry): """ Pre-processing function that turns a code into geometry(Point) for a list of floats. Params: ---------- geometry : String - String that represents a geometric coordinate of a point. Return: ---------- coord : List - List of cordenates. """ g = Geometry(geometry) coord = g.geojson['coordinates'] coord.reverse() return coord
def test_read_wkb_geometrycollection(self): """ read WKB GeometryCollection """ wkb = wkb_gc geom = Geometry(wkb) self.assertEquals(geom.type, "GeometryCollection") self.assertEquals(geom.srid, None) self.assertEquals(geom.dimz, False) self.assertEquals(geom.dimm, False) postgis_type = "geometry(GeometryCollection)" self.assertEquals(geom.postgis_type, postgis_type) self.assertEquals( geom.__repr__(), "<GeometryCollection: 'geometry(GeometryCollection)'>") geom.srid = geom.srid # clear cached WKB self.assertEquals(geom.__str__().lower(), wkb.lower()) self.assertEquals(geom.geometries[0].type, "Point") self.assertEquals(geom.geometries[1].type, "LineString")
async def render_geo_json(datasette, request, sql, columns, rows, database, table, query_name, view_name, data): result = await datasette.execute(database, sql) # create a new list which will store the single GeoJSON features feature_list = list() for row in result: # Is this a blatant Point object? if 'longitude' in row.keys() and 'latitude' in row.keys(): # https://geojson.org/geojson-spec.html#id2 point = geojson.Point((row['longitude'], row['latitude'])) # create a geojson feature feature = geojson.Feature(geometry=point, properties=dict(row)) # append the current feature to the list of all features feature_list.append(feature) # Otherwise, does this have a "the_geom" object, which was used in the old Carto database, which encodes geographical data as a string in the "well-known binary" format? elif 'the_geom' in row.keys(): feature = Geometry(row['the_geom']) feature_list.append(feature) else: # TODO: do we need to have error handling here? pass feature_collection = geojson.FeatureCollection(feature_list) body = geojson.dumps(feature_collection) content_type = "application/json; charset=utf-8" headers = {} status_code = 200 # add query / error handling! # Note: currently max result size is 1000 (can increase via settings.json) # OR look at using link setup for paging result sets # if required as outlined in datasette docs # if next_url: # headers["link"] = f'<{next_url}>; rel="next"' return Response(body=body, status=status_code, headers=headers, content_type=content_type)
def filter_safetyzone(request): #안심장소보기 global getGu safety_type = "" gu_type = "" mkurl = "" map = folium.Map(location=[37.55582994870823, 126.9726320033982], zoom_start=12) if request.method == "POST": filter_value = request.POST['safetyZone_filter'] safety_type = filter_value # 편의점을 선택한 경우 선택된 구를 출력 if (safety_type == "편의점"): mkurl = "safety_map/static/img/mk_cvs.png" #편의점 마커 이미지 safetyzone_ob_all = SafetyZone.objects.filter( gu=getGu) # 구 입력 방식 정해지면 '종로구'자리에 gu_type 넣으면 된다. # 경찰서, 지구대, 파출소를 선택한 경우 서울 전체 else: if (safety_type == "경찰서"): mkurl = "safety_map/static/img/mk_police_station.png" # 경찰서 마커 이미지 elif (safety_type == "지구대"): mkurl = "safety_map/static/img/mk_police_unit.png" # 지구대 마커 이미지 elif (safety_type == "파출소"): mkurl = "safety_map/static/img/mk_police_box.png" # 파출소 마커 이미지 safetyzone_ob_all = SafetyZone.objects.filter( safety_type=safety_type).all() # 마커 지도에 추가 for loc in safetyzone_ob_all: icon = folium.features.CustomIcon(icon_image=mkurl, icon_size=(50, 50)) gis = Geometry(loc.safety_loc.hex()[8:]) to_geojson = convert.wkt_to_geojson(str(gis.shapely)) to_coordinate = json.loads(to_geojson) marker = folium.map.Marker( [to_coordinate['coordinates'][0], to_coordinate['coordinates'][1]], icon=icon) marker.add_to(map) maps = map._repr_html_() return render(request, 'home.html', {'map': maps})
def test_execute(self): """ fdw.RandomPoint.execute check results """ options = { 'min_x': 10, 'max_x': 20, 'min_y': 30, 'max_y': 40, 'num': 99, 'srid': 4326 } columns = ['geom'] fdw = RandomPoint(options, columns) rows = fdw.execute([], columns) for row in rows: wkb = str(row["geom"]) point = Geometry(wkb) self.assertTrue(10 <= point.x <= 20) self.assertTrue(30 <= point.y <= 40)
def checkDanger(request): flag=0 msg="" if request.method=="POST": coord_x=request.POST.get("pos_x") coord_y=request.POST.get("pos_y") danger_area=Female2.objects.filter(female2_crime_type="전체_전체").all() for danger_point in danger_area: gis= Geometry(danger_point.female2_crime_loc.hex()[8:]) p=shape(gis.geojson) if p.contains(Point(float(coord_y),float(coord_x))): flag=1 if(request.user.is_authenticated): #username=request.user.username #sendSms(username) break else: msg="보호자에게 알림을 보내려면 로그인을 해주세요." return HttpResponse(json.dumps({'flag':flag,'msg':msg}),content_type="application/json")
def showKid(request): #아동필터 global g global getGu accident_type = "" loc_list = [] if request.method == 'POST': filter_value = request.POST["kid_filter"] accident_type = filter_value # 어린이 보행사고를 클릭한 경우 if filter_value == "스쿨존사고": accident_type = filter_value + "다발지역" elif filter_value == "어린이보행사고": accident_type = filter_value else: accident_type = filter_value kid_accident = Kid.objects.filter(gu=getGu, kid_accident_type=accident_type).all() #colormap_dept = cmp.StepColormap(colors=['#00ae53', '#86dc76', '#daf8aa','#ffe6a4', '#ff9a61', '#ee0028'], # vmin=10, vmax=310) for i in kid_accident: gis = Geometry(i.kid_accident_loc.hex()[8:]) to_geojson = convert.wkt_to_geojson(str(gis.shapely)) to_coordinate = json.loads(to_geojson) contain_coordinate = shape(to_coordinate) crime_location = {"type": "Feature", "geometry": to_coordinate} loc_list.append(crime_location) pistes = {"type": "FeatureCollection", "features": loc_list} map = folium.Map(location=[37.55582994870823, 126.9726320033982], zoom_start=15) folium.GeoJson(pistes).add_to(map) maps = map._repr_html_() return render(request, 'home.html', {'map': maps, 'pistes': pistes})
def to_convert_feature(geometry): """ Pre-processing function that turns a code into geometry(Feature) for a list of floats. Params: ---------- geometry : String - String that represents a geometric coordinate of a feature. Return: ---------- coord : List - List of cordenates. """ g = Geometry(geometry) coord = g.geojson['coordinates'][0][0] saida = [] for c in coord: c.reverse() saida.append(c) return saida
def test_modify_point(self): """ modify Point """ wkb = "010100000000000000000000000000000000000000" p = Geometry(wkb) oldx = p.x oldy = p.y oldsrid = p.srid self.assertFalse(p.dimz) self.assertFalse(p.dimm) newx = -99 newy = -101 newz = 88 newm = 8 newsrid = 900913 self.assertNotEquals(p.x, newx) self.assertNotEquals(p.y, newy) self.assertNotEquals(p.z, newz) self.assertNotEquals(p.m, newm) self.assertNotEquals(p.srid, newsrid) p.x = newx p.y = newy p.z = newz p.m = newm p.srid = newsrid self.assertEquals(p.x, newx) self.assertEquals(p.y, newy) self.assertEquals(p.z, newz) self.assertEquals(p.m, newm) self.assertEquals(p.srid, newsrid) self.assertNotEquals(p.__str__().lower(), wkb.lower()) p.x = oldx p.y = oldy p.srid = oldsrid p.dimz = None p.dimm = None self.assertEquals(p.__str__().lower(), wkb.lower())
def converterGeometryPoint(geometry): g = Geometry(geometry) coord = g.geojson['coordinates'] coord.reverse() return coord
def _get_predicates(self, quals): for qual in quals: if qual.field_name == 'query' and qual.operator == '=': return Geometry(qual.value) return None
def row_to_singer_record(catalog_entry, version, db_column_map, row, time_extracted): row_to_persist = {} for column_name, val in row.items(): property_type = catalog_entry.schema.properties[column_name].type property_format = catalog_entry.schema.properties[column_name].format db_column_type = db_column_map.get(column_name) if isinstance(val, datetime.datetime): if db_column_type in MYSQL_TIMESTAMP_TYPES: # The mysql-replication library creates datetimes from TIMESTAMP columns using fromtimestamp which # will use the local timezone thus we must set tzinfo accordingly See: # https://github.com/noplay/python-mysql-replication/blob/master/pymysqlreplication/row_event.py#L143 # -L145 timezone = tzlocal.get_localzone() local_datetime = timezone.localize(val) utc_datetime = local_datetime.astimezone(pytz.UTC) row_to_persist[column_name] = utc_datetime.isoformat() else: row_to_persist[column_name] = val.isoformat() + '+00:00' elif isinstance(val, datetime.date): row_to_persist[column_name] = val.isoformat() + 'T00:00:00+00:00' elif isinstance(val, datetime.timedelta): if property_format == 'time': # this should convert time column into 'HH:MM:SS' formatted string row_to_persist[column_name] = str(val) else: timedelta_from_epoch = datetime.datetime.utcfromtimestamp( 0) + val row_to_persist[column_name] = timedelta_from_epoch.isoformat( ) + '+00:00' elif db_column_type == FIELD_TYPE.JSON: row_to_persist[column_name] = json.dumps(json_bytes_to_string(val)) elif property_format == 'spatial': if val: srid = int.from_bytes(val[:4], byteorder='little') geom = Geometry(val[4:], srid=srid) row_to_persist[column_name] = json.dumps(geom.geojson) else: row_to_persist[column_name] = None elif isinstance(val, bytes): # encode bytes as hex bytes then to utf8 string row_to_persist[column_name] = codecs.encode(val, 'hex').decode('utf-8') elif 'boolean' in property_type or property_type == 'boolean': if val is None: boolean_representation = None elif val == 0: boolean_representation = False elif db_column_type == FIELD_TYPE.BIT: boolean_representation = int(val) != 0 else: boolean_representation = True row_to_persist[column_name] = boolean_representation else: row_to_persist[column_name] = val return singer.RecordMessage(stream=catalog_entry.stream, record=row_to_persist, version=version, time_extracted=time_extracted)