def main(args): features = [] if args.equator: geom = geojson.LineString([[-180, 0], [180, 0]]) features.append(geojson.Feature('equator', geom)) if args.tropics: cancer = geojson.LineString([[-180, 23.4378], [180, 23.4368]]) features.append(geojson.Feature('cancer', cancer)) capricorn = geojson.LineString([[-180, -23.4378], [180, -23.4378]]) features.append(geojson.Feature('capricorn', capricorn)) if args.lat: for top, right, bottom, left in latBand(args.lat): geom = geojson.Polygon([[top, left], [top, right], [bottom, right], [bottom, left]]) features.append(geojson.Feature(geometry=geom)) if args.long: for top, right, bottom, left in longBand(args.long): geom = geojson.Polygon([[top, left], [top, right], [bottom, right], [bottom, left]]) features.append(geojson.Feature(geometry=geom)) collection = geojson.FeatureCollection(features, indent=2) print geojson.dumps(collection)
def index(request): raw_points = points(48661914) matcher = AVAILABLE_MATCHERS['osrm'](raw_points) snapped_points = matcher.snapped_points() node_pairs = matcher.generate_node_pairs() way_querier = AVAILABLE_WAY_QUERIERS['fewest_nodes'](node_pairs) way_lookup = way_querier.way_lookup() raw_features = geojson.FeatureCollection([ build_raw_feature(way_id, raw_points, way.raw_indices) for way_id, way in way_lookup.iteritems() ]) snapped_features = geojson.FeatureCollection([ build_snapped_feature(way_id, snapped_points, way.raw_indices) for way_id, way in way_lookup.iteritems() ]) way_features = geojson.FeatureCollection([ build_way_feature(way_id, data, way_lookup[way_id]) for way_id, data in way_querier.ways_nodes.iteritems() ]) return render( request, 'cta_dump_viewer/index.html', Context({ 'raw_geojson': mark_safe(raw_features), 'rawline_geojson': mark_safe(geojson.LineString(raw_points)), 'snapped_geojson': mark_safe(snapped_features), 'snappedline_geojson': mark_safe(geojson.LineString(snapped_points)), 'ways_geojson': mark_safe(way_features) }))
def RouteSteps(steps): k, road, result = 0, [], [] for step in iterate(steps): maneuver, location = step['maneuver'], step['maneuver']['location'] ll = lonlat(location) road.append(ll) properties = { field.name: str(step[field.name]) for field in step.type.fields() if str(step[field.name]) != '""' } properties.update({ 'maneuver.' + field.name: str(maneuver[field.name]) for field in maneuver.type.fields() }) properties.update({ 'stroke': '#0000ff', 'stroke-opacity': 0.8, 'stroke-width': 15 }) result.append( geojson.Feature(geometry=geojson.LineString([ll, ll]), properties=properties)) road = geojson.Feature(geometry=geojson.LineString(road), properties={ 'stroke': '#0000ff', 'stroke-opacity': 0.5, 'stroke-width': 5 }) return [road, *result]
def test_invalid_linestring(self): with self.assertRaises(ValueError) as cm: geojson.LineString([(8.919, 44.4074)], validate=True) self.assertIn('must be an array of two or more positions', str(cm.exception)) with self.assertRaises(ValueError) as cm: geojson.LineString([(8.919, 44.4074), [3]], validate=True) self.assertIn('a position must have exactly 2 or 3 values', str(cm.exception))
def has_interior(): coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)] outer_line_string = geojson.LineString(coords, validate=True) r = 1 / 8 coords = [(0.5 + r * np.cos(θ), 0.5 + r * np.sin(θ)) for θ in np.linspace(0, 2 * π, 256)] inner_line_string = geojson.LineString(coords, validate=True) outer_feature = geojson.Feature(geometry=outer_line_string, properties={}) inner_feature = geojson.Feature(geometry=inner_line_string, properties={}) return geojson.FeatureCollection([outer_feature, inner_feature])
def output_geojson(self, INDENT=2, feature_type="line"): """Uses the geojson module to output a geojson file of the tropical cyclone. Default Arguments: INDENT = 2; used to provide indention to the output. Though it makes the output prettier and easier to read, it increases the file size. feature_type = "line"; determines the type of feature used in compiling the geoJSON file. "line" (default) indicates a geoJSON ``LineString`` while "point" indicates a geoJSON ``Point``. """ if feature_type.lower() not in ["point", "line"]: raise TypeError( "param feature_type must be either 'point' or 'line'.") ofn = "{}_{}_tracks_{}.geojson".format(self.atcfid, self.name, feature_type) # Ensure indention is an int INDENT = int(INDENT) feats = [] for trk in range(len(self.entry)): # Point feature if feature_type.lower() == "point": ls = geojson.Point((self.entry[trk].lon, self.entry[trk].lat)) # Polyline Feature elif feature_type.lower() == "line": ls = geojson.LineString([ (self.entry[trk].lon, self.entry[trk].lat), (self.entry[trk + 1].lon, self.entry[trk + 1].lat), ]) if trk != len(self.entry) - 1 else geojson.LineString([]) prp = { "ENTRY_ID": trk, "ATCFID": self.atcfid, "NAME": self.name, "ENTRY_TIME": self.entry[trk].entrytime.isoformat(), "LAT": self.entry[trk].lat, "LON": self.entry[trk].lon, "STATUS": self.entry[trk].status, "PEAK_WIND": self.entry[trk].wind if self.entry[trk].wind > 0 else None, "MSLP": self.entry[trk].mslp } feats.append(geojson.Feature(geometry=ls, properties=prp)) gjs = geojson.FeatureCollection(feats) with open(ofn, "w") as w: w.write(geojson.dumps(gjs, indent=INDENT))
def to_feature(self): pos_a = self.region.rooms[self.key_a].center_of_tile_to_devmap([self.x_a, self.y_a]) pos_b = self.region.rooms[self.key_b].center_of_tile_to_devmap([self.x_b, self.y_b]) properties = { "type":"connection" } return geojson.Feature(geometry=geojson.LineString([pos_a, pos_b]), properties=properties)
def way(self, w): if 'waterway' not in w.tags: return if 'name' not in w.tags: return if 'Kaveri' not in w.tags['name']: return # Tags must be copied when they need to be stored. properties = dict(w.tags) properties['id'] = w.id properties['updated_at'] = w.timestamp.strftime('%Y-%m-%d %H:%M:%S') properties['version'] = w.version # Turn nodes of the way into a geometry feature. geometry = geojson.LineString([(n.lon, n.lat) for n in w.nodes]) # Turn geometry into a geojson feature. feature = geojson.Feature(geometry=geometry, properties=properties) print(feature) # Append the feature. self.ways.append(feature)
def dump(list_data, data, filename, geometry='route'): with open(filename, 'w') as jfile: rnd_color = RandomColor() colors = rnd_color.generate(count=len(list_data)) features = [] index = 1 features.append(gs.MultiPoint(list(data.geo_data.values()))) for item in list_data: color = colors.pop() terminal = [item[0], item[-1]] # get route coords by road if geometry == 'graph': # graph geometry RP = data.indexToCoord(item) else: # osrm geometry RP = item.route() coords = gs.Feature(geometry=gs.LineString(RP), properties={'label': 'Route #{}'.format(index+1), 'color': color}) term = gs.Feature(geometry=gs.MultiPoint(data.indexToCoord(terminal)), properties={'label': 'Terminal #{}'.format(index+1), 'color': color}) index += 1 features.append(coords) features.append(term) feature_r = gs.FeatureCollection([features]) gs.dump(features, jfile)
def meanlines_to_geojson(lines): lines = [ geojson.Feature(geometry=geojson.LineString(line), id=idx) for idx, line in enumerate(lines) ] newFeature = geojson.FeatureCollection(lines) return newFeature
def export(cls, folder, h5_file): with tables.open_file(h5_file, mode="r") as h5: table = h5.root.trajectories.model_results timestamps = sorted(list(set([ x["time"] for x in table.iterrows() ]))) pts = [] features = [] for i, ts in enumerate(timestamps): points = MultiPoint([ Point(x['longitude'], x['latitude']) for x in table.where("""time == %s""" % ts) if x["latitude"] and x["longitude"] ]) cp = points.centroid.coords[0] geo_pt = geojson.Point(cp) pts.append(cp) feat = geojson.Feature(id=i, geometry=geo_pt, properties={ "time" : datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc).isoformat() }) features.append(feat) geo_ls = geojson.LineString(pts) features.append(geojson.Feature(geometry=geo_ls, id='path')) fc = geojson.FeatureCollection(features) if not os.path.exists(folder): os.makedirs(folder) filepath = os.path.join(folder, "full_trackline.geojson") with open(filepath, "wb") as r: r.write(geojson.dumps(fc).encode('utf-8'))
def determine_grid_river_axis(self, hexagons, grid, save=False): """ This function determines cells that other functions should look at to get the water levels. Function is only called at the initialization of Virtual River. This version of the function finds a 'wider axis' and includes multiple cells for each crossection (cell columns). """ def get_average(coor_list): average_list = [] for values in coor_list: average = sum(values) / len(values) average_list.append(average) return average_list x_all = [[] for i in range(15)] y_all = [[] for i in range(15)] for feature in hexagons.features: if feature.properties["ghost_hexagon"]: continue if not feature.properties["main_channel"]: continue shape = geometry.asShape(feature.geometry) x = shape.centroid.x y = shape.centroid.y column = feature.properties["column"] - 1 x_all[column].append(x) y_all[column].append(y) x_coor = get_average(x_all) y_coor = get_average(y_all) xy = list(zip(x_coor, y_coor)) line = geojson.LineString(xy) self.river_axis = geojson.Feature(id=0, geometry=line) river_axis = geometry.asShape(line) columns_covered = [] feature_ids = [] for feature in grid.features: if feature.properties["column"] is None: continue point = geometry.asShape(feature.geometry) distance = point.distance(river_axis) # change the value to compare here to determine the width of the # river axis that is looked at. 6 means 2 to 3 cells per grid # column. if distance < 6: column = feature.properties["column"] columns_covered.append(column) feature_ids.append(feature.id) for feature in grid.features: if feature.properties["column"] is None: feature.properties["river_axis"] = False continue if feature.id in feature_ids: feature.properties["river_axis"] = True else: feature.properties["river_axis"] = False if save: with open('river_axis_grid_wide.geojson', 'w') as f: geojson.dump(grid, f, sort_keys=True, indent=2) return grid
def geojson_ways(overpass_json): # first construct a node df for lookup of coordinates t = geojson_nodes(overpass_json) all_nodes = gpd.GeoDataFrame(t['features']) features = [] geometry = None for elem in overpass_json['elements']: elem_type = elem.get("type") if elem_type and elem_type == "way": coords = [] for node_id in elem['nodes']: # get the coordinates of the node from all_nodes df coords.append(all_nodes[all_nodes['id'] == node_id] ['geometry'].iloc[0]['coordinates']) geometry = geojson.LineString(coords) feature = geojson.Feature(id=elem['id'], geometry=geometry, properties=elem.get("tags")) features.append(feature) return geojson.FeatureCollection(features)
def to_geojson_obj(self, type='LineString', geojson_obj=None, name=''): """Format the object to a geojson file Args: type (str or RepType): Multiple type can be used with | or '|' for string (default is 'LineString') name (str): The name of the object (default is '') geojson_obj (object): The geojson object, if None a geojson object is created (default is None) Returns: object : The geojson object """ if isinstance(type, str): type = RepType(type).rep if geojson_obj == None: geojson_obj = geojson.FeatureCollection([]) if type & RepType.LineString: coords = [] for l in self.data: coords.append(tuple(l.geographic)) geojson_obj['features'].append( geojson.Feature(geometry=geojson.LineString(coords), properties={'name': name})) if type & RepType.Points: i = 0 for l in self.data: prop = l.to_dict(False) prop['time'] = l.time.strftime("%Y-%m-%d %H:%M:%S") prop['name'] = name if i % 50 == 0: geojson_obj['features'].append( geojson.Feature(geometry=geojson.Point( tuple(l.geographic)), properties=prop)) i += 1 return geojson_obj
def test_FeatureCollection_valid(): roax.geo.FeatureCollection().validate( geojson.FeatureCollection( [ geojson.Feature( geometry=geojson.Point([102.0, 0.5]), properties={"prop0": "value0"} ), geojson.Feature( geometry=geojson.LineString( [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]] ), properties={"prop0": "value0", "prop1": 0.0}, ), geojson.Feature( geometry=geojson.Polygon( [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0], ] ] ), properties={"prop0": "value0", "prop1": {"this": "that"}}, ), ] ) )
def Write_Geojson_Crop_Pre(data, output_file, ts_for_vis, time_window): #headers = ['unix_time', 'car_id', 'osm_id', 'gid', 'unix_time_pre', 'gid_pre', 'pick_or_drop', 'speed', 'linestring'] features = [] for item in data: points_in_line = [] time_pre = item[4] time_current = item[0] if time_current == time_pre: continue line = item[8] line = line.split('(')[1] line = line.split(')')[0] lst = line.split(',') for i in range(0,len(lst)): tmp = lst[i].split() points_in_line.append([float(tmp[0]),float(tmp[1])]) start_index = 0 end_index = len(points_in_line) if time_pre < ts_for_vis and time_current <= ts_for_vis + time_window: start_index = int((1 - (time_current - ts_for_vis) / float(time_current - time_pre))*end_index) time_pre = ts_for_vis elif time_pre >= ts_for_vis and time_current > ts_for_vis + time_window: end_index = int((ts_for_vis + time_window - time_pre) / float(time_current - time_pre)*end_index) time_current = ts_for_vis + time_window if len(range(start_index,end_index)) < 2: continue time_string = datetime.datetime.utcfromtimestamp(time_current + 3600*8).strftime('%Y-%m-%d %H:%M:%S') features.append(geojson.Feature(geometry=geojson.LineString(points_in_line[start_index:end_index]), properties={'ABSTIME':time_current,'TIME':time_string,'CAR_ID':item[1], 'OSM_ID': item[2], 'GID': item[3], 'GID_pre': item[5], 'Pick_or_drop':item[6], "ABS_TIME_PRE":time_pre,"Speed":item[7]})) geom_in_geojson = geojson.FeatureCollection(features) with open(output_file, 'w') as o: geojson.dump(geom_in_geojson, o)
def extractGeoms(self, pairsDF, sLat="sLat", sLon="sLon", dLat="dLat", dLon="dLon", verbose=False): ''' Runs the routing command on all the rows in the pairsDF --- variables --- pairsDF [pandas DataFrame] - dataframe containing two sets of latitude and longitude as defined by the optional commands [optional] sLat, sLon, dLat, dLon [string] - field name containing the lats and longs --- returns --- [geopandas dataframe] - contains two(ish?) columns - the index of the input pairs DF ''' allRes = [] for idx, row in pairsDF.iterrows(): if verbose: print idx location = "%s,%s;%s,%s" % (row[sLon], row[sLat], row[dLon], row[dLat]) baseUrl = "%s/route/v1/driving/%s?overview=simplified&geometries=geojson" % ( self.osrmHeader, location) try: r = url.urlopen(baseUrl) curRes = json.loads(r.read().decode('utf-8')) curCoords = curRes['routes'][0]['geometry']['coordinates'] curGeom = geojson.LineString(curCoords) allRes.append([idx, shape(curGeom)]) except: print("There was an error with row %s" % idx) final = pd.DataFrame(allRes, columns=['ID', 'geometry']) final = gpd.GeoDataFrame(final, geometry='geometry') return final
def es_geoshape_to_geojson(index, doc_type, geoshape_field, outfile, query={}): #input: ES index, doctype, and field that is mapped as a geoshape #output: Geojson feature collection es_full_url = 'http://' + ES_username + ':' + ES_password + '@' + ES_url + ':9200' es = Elasticsearch(es_full_url) features = [] docs = helpers.scan(es, index=index, doc_type=doc_type, query=json.dumps(query)) for doc in docs: #define the geojson shape type based on ES geoshape type if doc['_source'][geoshape_field]['type'].lower() == 'point': shape = geojson.Point( doc['_source'][geoshape_field]['coordinates']) if doc['_source'][geoshape_field]['type'].lower() == 'linestring': shape = geojson.LineString( doc['_source'][geoshape_field]['coordinates']) if doc['_source'][geoshape_field]['type'].lower() == 'polygon': shape = geojson.Polygon( doc['_source'][geoshape_field]['coordinates']) if doc['_source'][geoshape_field]['type'].lower() == 'multipolygon': shape = geojson.MultiPolygon( doc['_source'][geoshape_field]['coordinates']) #print geojson.is_valid(shape) props = deepcopy(doc['_source']) props.pop(geoshape_field, None) features.append(geojson.Feature(geometry=shape, properties=props)) with open(outfile, 'w') as out: geojson.dump(geojson.FeatureCollection(features), out)
def to_geojson( self, draw_points=False, write_to=None, linestring_props=None, multipoint_props=None, ): geometry = geojson.Feature( geometry=geojson.LineString(self.to_lng_lat_tuples()), properties=linestring_props, ) features = geojson.FeatureCollection([geometry]) if draw_points: points = geojson.Feature( geometry=geojson.MultiPoint([(p.lng, p.lat) for p in self.coords]), properties=multipoint_props, ) features = geojson.FeatureCollection([geometry, points]) if write_to: with open(write_to, "w") as f: f.write(geojson.dumps(features)) else: return features
def convertTOGEOJSON(data, ftype): """ converts coordinates to geojson """ ftype = ftype.lower() if ftype == "point": result_feat = [] for i in range(0, len(data)): point = geojson.Point(data[i]) result_feat.append(geojson.Feature(geometry=point)) result_feat = geojson.FeatureCollection(result_feat) # pp.pprint(collection) # valid return result_feat if ftype == "polygon": polygon = geojson.Polygon(data) # print(polygon) # valid return polygon elif ftype == "linestring": linestring = geojson.LineString(data) # print(linestring) #valid return (linestring) elif ftype == "multilinestring": mls = geojson.MultiLineString(data) # print(mls) # valid return mls else: print("\nwrong argument\n")
def create_features(df): features = [] properties = [ c for c in list(df) if c not in ['name', 'geom', 'timeseries'] ] for _, row in df.iterrows(): coords = extract_coordinates(row) name = row['name'] if len(coords) == 1: feature = gj.Feature(id=name, geometry=gj.Point(coords[0])) elif row['type'] == 'hub_relation': feature = gj.Feature(id=name, geometry=gj.Polygon([coords])) else: feature = gj.Feature(id=name, geometry=gj.LineString(coords)) for prop in properties: prop_value = row[prop] if pd.notnull(prop_value): if prop == 'hubs': prop_value = prop_value.split(',') feature['properties'][prop] = prop_value if 'timeseries' in df: ts_value = row['timeseries'] if pd.notnull(ts_value): for ts in ts_value.split(','): feature['properties'][ts] = list(timeseries_df[name + '.' + ts]) features.append(feature) return features
def __json_iterator(self, output_type): """ Iterates over all linestring coordinates and adds a 'visit time' to each pair. The 'visit time' explains the timestamp that the point is visited """ feature_list = [] for x, item in enumerate(self.json_input['features']): if x == 0: time = self.start_time else: distance_from_start = item['properties']['distance'] time = int(self.start_time + distance_from_start / self.m_per_second) this_coords = [_ for sublist in item['geometry']['coordinates'] for _ in sublist] for i, pair in enumerate(this_coords): j = i - 1 if i == 0: pair.append(time) else: line_length = self.__get_distance(this_coords[j], pair) time += int(line_length / self.m_per_second) pair.append(time) if output_type == "json": this_linestring = geojson.LineString(this_coords) this_feature = Feature(geometry=this_linestring, type="Feature") feature_list.append(this_feature) elif output_type == "waypoints": feature_list.append(Waypoints(this_coords)) return feature_list
def tryToConvertToPolygon(tags, lines, polygonize, isMultiPolygon = False): """ Creates a Polygon or LineString based on the given lines tags: tags of the base object lines: coordinates (basically nested lists) polygonize: boolean, if True -> tries to convert every Line to Polygon isMultiPolygon: boolean, if each line is an extra polygon else lines = [boundary, holes..] """ # as sometimes tags like "area":"no" exists, which are obviously no polygons tags = {tag: v for tag, v in tags.items() if not v == "no"} # osm-multipolygon: means just as complex area ... but geojson polygons can also handle holes # sometimes they are real multipolygons? (see Dresdener Heide) --> isMultiPolygon if POLYGON_TAGS.intersection(tags) or tags.get("type") == "multipolygon" or polygonize: if isMultiPolygon: # creating a polygon array for each line (only exterior lines, no holes currently) lines = [[line] for line in lines] polygon = geojson.MultiPolygon(lines) else: polygon = geojson.Polygon(lines) if not polygon.errors(): return polygon elif not polygonize: # with polygonize == true it is expected that this wont work every time logging.debug("Could not be converted to a polygon with tags {}".format(tags)) if len(lines) == 1: return geojson.LineString(lines[0], validate=True) else: if LINESTRING_TAGS.intersection(tags): logging.debug("To many lines for a simple line for object with tags: {}".format(tags)) return geojson.MultiLineString(lines, validate=True)
def save_geojson(paths, savepath): palette = { 'DOF':'#1f78b4', 'CTA':'#33a02c', 'Speed':'#6a3d9a', 'Red light':'#a6cee3', 'Chicago Parking Meter':'#b2df8a', 'Miscellaneous/Other':'#cab2d6', 'Streets and San':'#e31a1c', 'LAZ':'#fb9a99', 'CPD':'#fdbf6f', 'SERCO':'#ff7f00' } features = [] for officer, geoms in paths.items(): officer_dept = officer.split('|')[1] color = palette[officer_dept] if not geoms: continue for geom in geoms: ls = geojson.LineString(geom) feature = geojson.Feature(geometry=ls, properties={'stroke':color, 'stroke-width':1}) features.append(feature) fh = open(savepath, 'w') results = geojson.FeatureCollection(features) geojson.dump(results, fh) fh.close() return results
def toGeoJson(data, dtype): """formats all data input to valid geojson """ dtype = dtype.lower() if dtype == "point": collection = [] for i in range(0, len(data)): point = geojson.Point(data[i]) collection.append(geojson.Feature(geometry=point)) collection = geojson.FeatureCollection(collection) # pp.pprint(collection) # valid return collection if dtype == "polygon": polygon = geojson.Polygon(data) # print(polygon) # valid return polygon elif dtype == "linestring": linestring = geojson.LineString(data) # print(linestring) #valid return (linestring) elif dtype == "multilinestring": mls = geojson.MultiLineString(data) # print(mls) # valid return mls else: print("\nBAD ARGUMENT\n")
def Write_Geojson_Pre(data, output_file): #headers = ['unix_time', 'car_id', 'osm_id', 'gid', 'unix_time_pre', 'gid_pre', 'pick_or_drop', 'speed', 'linestring'] features = [] for item in data: points_in_line = [] line = item[8] line = line.split('(')[1] line = line.split(')')[0] lst = line.split(',') for i in range(0, len(lst)): tmp = lst[i].split() points_in_line.append([float(tmp[0]), float(tmp[1])]) time_string = datetime.datetime.utcfromtimestamp( item[0] + 3600 * 8).strftime('%Y-%m-%d %H:%M:%S') features.append( geojson.Feature(geometry=geojson.LineString(points_in_line), properties={ 'ABSTIME': item[0], 'TIME': time_string, 'CAR_ID': item[1], 'OSM_ID': item[2], 'GID': item[3], 'GID_pre': item[5], 'Pick_or_drop': item[6], "ABS_TIME_PRE": item[4], "Speed": item[7] })) geom_in_geojson = geojson.FeatureCollection(features) with open(output_file, 'w') as o: geojson.dump(geom_in_geojson, o)
def test_map_linestring(self): g = geojson.LineString( [(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)]) result = map_coords(lambda x: x, g) self.assertEqual(result['type'], 'LineString') self.assertEqual(result['coordinates'][0], (3.78, 9.28)) self.assertEqual(result['coordinates'][-1], (3.78, 9.28))
def edgesGenerator(graph, interleaved=True): edges = graph.edges(data=True) for i, (node1, node2, data) in enumerate(edges): x1 = graph.node[node1]['longitude'] x2 = graph.node[node2]['longitude'] y1 = graph.node[node1]['latitude'] y2 = graph.node[node2]['latitude'] minx = min([x1, x2]) maxx = max([x1, x2]) miny = min([y1, y2]) maxy = max([y1, y2]) linestring = geojson.LineString([(x1, y1), (x2, y2)]) feature = geojson.Feature(geometry=linestring, properties={ "node1": node1, "node2": node2 }, id=data['osmid']) if interleaved: yield (i, (minx, miny, maxx, maxy), geojson.dumps(feature, sort_keys=True)) else: yield (i, (minx, maxx, miny, maxy), geojson.dumps(feature, sort_keys=True))
def gen_geojson(bus_lines): lines_geojson = [] for line in bus_lines: feature_collection = [] points = [] line_name = line['name'] stations = line['stations'] for station in stations: station_name = station['name'] latlng = list(map(float, station['xy_coords'].split(';'))) points.append(latlng) geometry = geojson.Point(tuple(latlng)) feature_collection.append( geojson.Feature(geometry=geometry, properties={ "info": "线路:{line_name}<br>" "车站:{station_name}<br>" "经纬度:{latlng}<br>".format( line_name=line_name, station_name=station_name, latlng=latlng) })) feature_collection.append( geojson.Feature(geometry=geojson.LineString(points))) lines_geojson.append(geojson.FeatureCollection(feature_collection)) return lines_geojson
def geometry(self): try: if self.type() == 'node': if not self.lon() or not self.lat(): self._raiseException('Cannot build geometry: geometry information not included.') return geojson.Point((self.lon(), self.lat())) elif self.type() == 'way': if not self.__getElement('geometry'): self._raiseException('Cannot build geometry: geometry information not included.') cs = self.__geometry_csToList(self.__getElement('geometry')) if self.__geometry_equal(cs[0], cs[-1]): return geojson.Polygon([cs]) else: return geojson.LineString(cs) elif self.type() == 'relation': members = copy.deepcopy(self.__members()) membersOuter = self.__geometry_extract(members, 'outer') if len(membersOuter) == 0: self._raiseException('Cannot build geometry: no outer rings found.') membersInner = self.__geometry_extract(members, 'inner') ringsOuter = self.__geometry_buildRings(membersOuter) ringsInner = self.__geometry_buildRings(membersInner) ringsOuter = self.__geometry_orientRings(ringsOuter, positive=True) ringsInner = self.__geometry_orientRings(ringsInner, positive=False) polygons = self.__geometry_buildPolygons(ringsOuter, ringsInner) if len(polygons) > 1: return geojson.MultiPolygon(polygons) else: return geojson.Polygon(polygons[0]) else: self._raiseException('Cannot build geometry: type of element unknown.') except Exception as e: _extendAndRaiseException(e, ' ({}/{})'.format(self.type(), self.id()))