Python geojson.LineString() Examples

The following are 11 code examples of geojson.LineString(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module geojson , or try the search function .
Example #1
Source File: meshing.py    From icepack with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: contour.py    From geojsoncontour with MIT License 5 votes vote down vote up
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) 
Example #3
Source File: jsoncodec.py    From ngsi-timeseries-api with MIT License 5 votes vote down vote up
def line_to_json_rep(line: SlfLine) -> LineString:
    ps = list_point_tuples(line)
    return LineString(ps) 
Example #4
Source File: meshing_test.py    From icepack with GNU General Public License v3.0 5 votes vote down vote up
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]) 
Example #5
Source File: spatial.py    From swmmio with MIT License 5 votes vote down vote up
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) 
Example #6
Source File: element.py    From osm-python-tools with GNU General Public License v3.0 5 votes vote down vote up
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())) 
Example #7
Source File: road.py    From robosat with MIT License 4 votes vote down vote up
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) 
Example #8
Source File: api.py    From overpass-api-python-wrapper with Apache License 2.0 4 votes vote down vote up
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) 
Example #9
Source File: bus_router.py    From bus-router with MIT License 4 votes vote down vote up
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) 
Example #10
Source File: run.py    From Wayfinder3D with MIT License 4 votes vote down vote up
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 
Example #11
Source File: functions.py    From swmmio with MIT License 4 votes vote down vote up
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