本文整理汇总了Python中geojson.LineString方法的典型用法代码示例。如果您正苦于以下问题:Python geojson.LineString方法的具体用法?Python geojson.LineString怎么用?Python geojson.LineString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类geojson
的用法示例。
在下文中一共展示了geojson.LineString方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _flatten
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def _flatten(features):
r"""Expand all MultiLineString features in the input list to individual
LineString features"""
flat_features = []
for feature in features:
if feature['geometry']['type'] == 'LineString':
flat_features.append(feature)
if feature['geometry']['type'] == 'MultiLineString':
properties = feature['properties']
for line_string in feature['geometry']['coordinates']:
geometry = geojson.LineString(coordinates=line_string)
flat_feature = geojson.Feature(geometry=geometry,
properties=properties)
flat_features.append(flat_feature)
return flat_features
示例2: contour_to_geojson
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def contour_to_geojson(contour, geojson_filepath=None, min_angle_deg=None,
ndigits=5, unit='', stroke_width=1, geojson_properties=None, strdump=False,
serialize=True):
"""Transform matplotlib.contour to geojson."""
collections = contour.collections
contour_index = 0
line_features = []
for collection in collections:
color = collection.get_edgecolor()
for path in collection.get_paths():
v = path.vertices
if len(v) < 3:
continue
coordinates = keep_high_angle(v, min_angle_deg) if min_angle_deg else v
coordinates = np.around(coordinates, ndigits) if ndigits is not None else coordinates
line = LineString(coordinates.tolist())
properties = {
"stroke-width": stroke_width,
"stroke": rgb2hex(color[0]),
"title": "%.2f" % contour.levels[contour_index] + ' ' + unit,
"level-value": float("%.6f" % contour.levels[contour_index]),
"level-index": contour_index
}
if geojson_properties:
properties.update(geojson_properties)
line_features.append(Feature(geometry=line, properties=properties))
contour_index += 1
feature_collection = FeatureCollection(line_features)
return _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize)
示例3: line_to_json_rep
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def line_to_json_rep(line: SlfLine) -> LineString:
ps = list_point_tuples(line)
return LineString(ps)
示例4: has_interior
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def has_interior():
coords = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (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])
示例5: coords_series_to_geometry
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def coords_series_to_geometry(coords, geomtype='linestring', dtype='geojson'):
"""
Convert a series of coords (list of list(s)) to a series of geometry objects.
:param coords: series of lists of xy coordinates
:param geomtype: geometry type of target
:param dtype: format of geometry objects to be created ('geojson', 'shapely')
:return: series of geometry objects
>>> import swmmio
>>> model = swmmio.Model(MODEL_FULL_FEATURES_XY)
>>> nodes = model.nodes()
>>> geoms = coords_series_to_geometry(nodes['coords'], geomtype='point')
>>> geoms.iloc[0]
{"coordinates": [2748073.3060000003, 1117746.087], "type": "Point"}
"""
# detect whether LineString or Point should be used
geomtype = geomtype.lower()
if geomtype == 'linestring':
geoms = [LineString(latlngs) for latlngs in coords]
elif geomtype == 'point':
geoms = [Point(latlngs[0]) for latlngs in coords]
elif geomtype == 'polygon':
geoms = [Polygon([latlngs]) for latlngs in coords]
if dtype.lower() == 'shape':
# convert to shapely objects
try:
from shapely.geometry import shape
except ImportError:
raise ImportError('shapely module needed. Install it via GeoPandas with conda: ',
'conda install geopandas')
geoms = [shape(g) for g in geoms]
return pd.Series(index=coords.index, name='geometry', data=geoms)
示例6: geometry
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
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()))
示例7: way
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def way(self, w):
if "highway" not in w.tags:
return
if w.tags["highway"] not in self.road_filter:
return
left_hard_shoulder_width = self.highway_attributes[w.tags["highway"]]["left_hard_shoulder_width"]
lane_width = self.highway_attributes[w.tags["highway"]]["lane_width"]
lanes = self.highway_attributes[w.tags["highway"]]["lanes"]
right_hard_shoulder_width = self.highway_attributes[w.tags["highway"]]["right_hard_shoulder_width"]
if "oneway" not in w.tags:
lanes = lanes * 2
elif w.tags["oneway"] == "no":
lanes = lanes * 2
if "lanes" in w.tags:
try:
# Roads have at least one lane; guard against data issues.
lanes = max(int(w.tags["lanes"]), 1)
# Todo: take into account related lane tags
# https://wiki.openstreetmap.org/wiki/Tag:busway%3Dlane
# https://wiki.openstreetmap.org/wiki/Tag:cycleway%3Dlane
# https://wiki.openstreetmap.org/wiki/Key:parking:lane
except ValueError:
print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr)
road_width = left_hard_shoulder_width + lane_width * lanes + right_hard_shoulder_width
if "width" in w.tags:
try:
# At least one meter wide, for road classes specified above
road_width = max(float(w.tags["width"]), 1.0)
# Todo: handle optional units such as "2 m"
# https://wiki.openstreetmap.org/wiki/Key:width
except ValueError:
print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr)
geometry = geojson.LineString([(n.lon, n.lat) for n in w.nodes])
shape = shapely.geometry.shape(geometry)
geometry_buffer = shape.buffer(math.degrees(road_width / 2.0 / self.EARTH_MEAN_RADIUS))
if shape.is_valid:
feature = geojson.Feature(geometry=shapely.geometry.mapping(geometry_buffer))
self.storage.add(feature)
else:
print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr)
示例8: _as_geojson
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def _as_geojson(self, elements):
features = []
geometry = None
for elem in elements:
elem_type = elem.get("type")
elem_tags = elem.get("tags")
elem_geom = elem.get("geometry", [])
if elem_type == "node":
# Create Point geometry
geometry = geojson.Point((elem.get("lon"), elem.get("lat")))
elif elem_type == "way":
# Create LineString geometry
geometry = geojson.LineString([(coords["lon"], coords["lat"]) for coords in elem_geom])
elif elem_type == "relation":
# Initialize polygon list
polygons = []
# First obtain the outer polygons
for member in elem.get("members", []):
if member["role"] == "outer":
points = [(coords["lon"], coords["lat"]) for coords in member.get("geometry", [])]
# Check that the outer polygon is complete
if points and points[-1] == points[0]:
polygons.append([points])
else:
raise UnknownOverpassError("Received corrupt data from Overpass (incomplete polygon).")
# Then get the inner polygons
for member in elem.get("members", []):
if member["role"] == "inner":
points = [(coords["lon"], coords["lat"]) for coords in member.get("geometry", [])]
# Check that the inner polygon is complete
if points and points[-1] == points[0]:
# We need to check to which outer polygon the inner polygon belongs
point = Point(points[0])
check = False
for poly in polygons:
polygon = Polygon(poly[0])
if polygon.contains(point):
poly.append(points)
check = True
break
if not check:
raise UnknownOverpassError("Received corrupt data from Overpass (inner polygon cannot "
"be matched to outer polygon).")
else:
raise UnknownOverpassError("Received corrupt data from Overpass (incomplete polygon).")
# Finally create MultiPolygon geometry
if polygons:
geometry = geojson.MultiPolygon(polygons)
else:
raise UnknownOverpassError("Received corrupt data from Overpass (invalid element).")
if geometry:
feature = geojson.Feature(
id=elem["id"],
geometry=geometry,
properties=elem_tags
)
features.append(feature)
return geojson.FeatureCollection(features)
示例9: shapesToGeojson
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def shapesToGeojson():
json_data=open('data.txt')
datadir = os.path.join(os.getcwd(), 'data')
gtfsdir = os.path.join(datadir, 'gtfs')
geojsondir = os.path.join(datadir, 'geojson')
data = json.load(json_data, object_hook=_decode_dict)
json_data.close()
with open(gtfsdir + "/shapes.txt", 'rb') as shapesfile:
shapesreader = csv.DictReader(shapesfile)
keys = shapesreader.fieldnames
jsonpoints = []
features = []
currentTrip = ''
for i, point in enumerate(shapesreader):
if point['shape_pt_sequence'] == '0':
print 'creating trip'
currentTrip = point['shape_id']
if i > 0:
ls = LineString(jsonpoints)
feature = Feature(geometry=ls, properties={"shape_id": currentTrip})
# print feature
features.append(feature)
jsonpoints = []
else:
pnt = (float(point['shape_pt_lon']), float(point['shape_pt_lat']))
# print pnt
jsonpoints.append(pnt)
# write linestring for last shape
ls = LineString(jsonpoints)
feature = Feature(geometry=ls, properties={"shape_id": currentTrip})
print feature
features.append(feature)
jsonpoints = []
fc = FeatureCollection(features)
print fc
geojsonfile = os.path.join(geojsondir, 'shapes.geojson')
with open(geojsonfile, 'wb') as tripgeo:
geojson.dump(fc, tripgeo)
示例10: multimodal_directions
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def multimodal_directions(origin, destination, modes, API_KEY):
# Store GeoJSON features in a list
results = []
# Store durations and start / stop times
durations = []
starttimes = []
endtimes = []
for mode in modes:
# Get data from Google Maps Directions API
data = gmaps_directions(origin, destination, mode, API_KEY)
# Check to see if no routes returned.
if len(data['routes']) == 0:
sys.exit("Sorry, directions are not available for {} from {} to {}".format(mode, origin, destination))
# Get duration in seconds
if 'duration_in_traffic' in data['routes'][0]['legs'][0]:
duration = data['routes'][0]['legs'][0]['duration_in_traffic']['value']
else:
duration = data['routes'][0]['legs'][0]['duration']['value']
# Calculate arrival time
arrival_time = departure_time + timedelta(0, duration)
# Get polyline
polyline = data['routes'][0]['overview_polyline']['points']
# Decode polyline
decoded_polyline = decode_polyline(polyline)
# Create LineString
linestring = LineString(decoded_polyline)
# Create GeoJSON properties
properties={'mode': mode, 'duration': duration,
'start': departure_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3], 'end': arrival_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}
# Create GeoJSON feature
feature = Feature(geometry=linestring, properties=properties)
# Store feature in results list
results.append(feature)
# Store duration and start/stop times in lists
durations.append(duration)
starttimes.append(departure_time)
endtimes.append(arrival_time)
# Convert list of features to GeoJSON FeatureCollection
feature_collection = FeatureCollection(results)
return feature_collection, durations, starttimes, endtimes
示例11: model_to_networkx
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import LineString [as 别名]
def model_to_networkx(model, drop_cycles=True):
from swmmio.utils.dataframes import dataframe_from_rpt
'''
Networkx MultiDiGraph representation of the model
'''
from geojson import Point, LineString
def multidigraph_from_edges(edges, source, target):
'''
create a MultiDiGraph from a dataframe of edges, using the row index
as the key in the MultiDiGraph
'''
us = edges[source]
vs = edges[target]
keys = edges.index
data = edges.drop([source, target], axis=1)
d_dicts = data.to_dict(orient='records')
G = nx.MultiDiGraph()
G.add_edges_from(zip(us, vs, keys, d_dicts))
return G
# parse swmm model results with swmmio, concat all links into one dataframe
nodes = model.nodes()
links = model.links()
links['facilityid'] = links.index
# create a nx.MultiDiGraph from the combined model links, add node data, set CRS
G = multidigraph_from_edges(links, 'InletNode', target='OutletNode')
G.add_nodes_from(zip(nodes.index, nodes.to_dict(orient='records')))
# create geojson geometry objects for each graph element
for u, v, k, coords in G.edges(data='coords', keys=True):
if coords:
G[u][v][k]['geometry'] = LineString(coords)
for n, coords in G.nodes(data='coords'):
if coords:
G.nodes[n]['geometry'] = Point(coords[0])
if drop_cycles:
# remove cycles
cycles = list(nx.simple_cycles(G))
if len(cycles) > 0:
warnings.warn(f'cycles detected and removed: {cycles}')
G.remove_edges_from(cycles)
G.graph['crs'] = model.crs
return G