Beispiel #1
0
    def callback_flatten_each(feature, feature_index, multi_feature_index):
        nonlocal length
        nonlocal closest_pt

        coords = get_coords(feature)
        for i, coord in enumerate(coords[:-1]):
            # start
            start = Feature(geometry=Point(coord))
            start.properties = {"dist": dist(point, start, options)}
            # stop
            stop = Feature(geometry=Point(coords[i + 1]))
            stop.properties = {"dist": dist(point, stop, options)}
            # section length
            section_length = dist(start, stop, options)
            # perpendicular
            height_distance = max(start.properties["dist"],
                                  stop.properties["dist"])
            direction = bearing(start, stop)

            perpendicular_pt1 = destination(Feature(geometry=point),
                                            height_distance, direction + 90,
                                            options)
            perpendicular_pt2 = destination(Feature(geometry=point),
                                            height_distance, direction - 90,
                                            options)
            intersect = line_intersect(
                Feature(geometry=LineString([
                    get_coord(perpendicular_pt1),
                    get_coord(perpendicular_pt2)
                ])),
                Feature(geometry=LineString(
                    [get_coord(start), get_coord(stop)])),
            )
            intersect_pt = None
            if len(intersect["features"]) > 0:
                intersect_pt = intersect["features"][0]
                intersect_pt.properties["dist"] = dist(point, intersect_pt,
                                                       options)
                intersect_pt.properties["location"] = length + dist(
                    start, intersect_pt, options)

            if start.properties["dist"] < closest_pt.properties["dist"]:
                closest_pt = start
                closest_pt.properties["index"] = i
                closest_pt.properties["location"] = length

            if stop.properties["dist"] < closest_pt.properties["dist"]:
                closest_pt = stop
                closest_pt.properties["index"] = i + 1
                closest_pt.properties["location"] = length + section_length

            if (intersect_pt and intersect_pt.properties["dist"] <
                    closest_pt.properties["dist"]):
                closest_pt = intersect_pt
                closest_pt.properties["index"] = i

            # update length
            length += section_length
        # process all Features
        return True
Beispiel #2
0
def bbox_polygon(bbox: list, properties: dict = {}) -> Feature:
    """
    To generate a Polygon Feature for the bounding box generated using bbox.

    :param bbox: bounding box generated for a geojson.
    :param properties: properties to be added to the returned feature.
    :return: polygon for the given bounding box coordinates.

    Example :

    >>> from turfpy.measurement import bbox_polygon, bbox
    >>> from geojson import Polygon

    >>> p = Polygon([((2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),
    ... (2.38, 57.322))])
    >>> bb = bbox(p)
    >>> feature = bbox_polygon(bb)
    """
    west = float(bbox[0])
    south = float(bbox[1])
    east = float(bbox[2])
    north = float(bbox[3])

    if len(bbox) == 6:
        raise Exception("bbox-polygon does not support BBox with 6 positions")

    low_left = (west, south)
    top_left = (west, north)
    top_right = (east, north)
    low_right = (east, south)

    bbox_polygon = Polygon([(low_left, low_right, top_right, top_left,
                             low_left)])
    feature_bbox = Feature(geometry=bbox_polygon)

    if "properties" in properties:
        feature_bbox.properties = properties["properties"]
    elif "properties" not in properties:
        feature_bbox.properties = {}

    if "id" in properties:
        feature_bbox.id = properties["id"]

    if "bbox" in properties:
        feature_bbox.bbox = properties["bbox"]

    return feature_bbox
Beispiel #3
0
def center(geojson, properties: Optional[dict] = None) -> Feature:
    """
    Takes a Feature or FeatureCollection and returns the absolute center point of all
    features.

    :param geojson: GeoJSON for which centered to be calculated.
    :param properties: Optional parameters to be set to the generated feature.
    :return: Point feature for the center.

    Example :

    >>> from turfpy.measurement import center
    >>> from geojson import Feature, FeatureCollection, Point

    >>> f1 = Feature(geometry=Point((-97.522259, 35.4691)))
    >>> f2 = Feature(geometry=Point((-97.502754, 35.463455)))
    >>> f3 = Feature(geometry=Point((-97.508269, 35.463245)))
    >>> feature_collection = FeatureCollection([f1, f2, f3])
    >>> feature = center(feature_collection)
    """
    bounding_box = bbox(geojson)
    x = (bounding_box[0] + bounding_box[2]) / 2
    y = (bounding_box[1] + bounding_box[3]) / 2

    point = Point((x, y))

    center_feature = Feature(geometry=point)

    if properties is None:
        properties = dict()
    if "properties" in properties:
        center_feature.properties = properties["properties"]
    elif "properties" not in properties:
        center_feature.properties = {}

    if "id" in properties:
        center_feature.id = properties["id"]

    if "bbox" in properties:
        center_feature.bbox = properties["bbox"]

    return center_feature
Beispiel #4
0
qres = g.query("""
    PREFIX sdo: <http://schema.org/>    
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX dc: <http://purl.org/dc/terms/>

    SELECT DISTINCT ?newsitemlabel ?label ?lon ?lat ?newsitemdate ?url
       WHERE {
          ?item rdfs:label ?label .
          ?item sdo:geo ?geo .
          ?geo sdo:latitude ?lat .
          ?geo sdo:longitude ?lon .
          ?newsitem sdo:about ?item .
          ?newsitem dc:title ?newsitemlabel .
          ?newsitem sdo:datePublished ?newsitemdate .
          ?newsitem sdo:url ?url .
       }""")

for row in qres:
    p = Point((float(row[2].value), float(row[3].value)))
    desc = f"{row[1]}: {row[4]}<br><a href='{row[5]}'>{row[0]}</a>"
    f = Feature(geometry=p)
    f.properties = {
        "description": desc,
        "name": row[1],
        "time": row[4],
        "url": row[5]
    }
    geoj.add_feature(f)

geoj.save("./data/map.json")
Beispiel #5
0
   WHERE {
      ?item rdfs:label ?label .
      ?item sdo:geo ?geo .
      ?geo sdo:latitude ?lat .
      ?geo sdo:longitude ?lon .
      ?newsitem sdo:about ?item .
      ?newsitem dc:identifier ?post_id .
}  ORDER BY ?post_id
""")

post_ids = set([row['post_id'].value for row in qres])

for post_id in post_ids:
    geoj = pygeoj.new()
    logger.info(f"Working on {post_id}")
    for row in qres:
        if int(row["post_id"].value) == int(post_id):
            p = Point((float(row["lon"].value), float(row["lat"].value)))
            f = Feature(geometry=p)
            f.properties = {
                "description": row['label'].value,
                "name": row['label'].value
            }
            geoj.add_feature(f)

    if len(geoj) > 0:
        logger.info(f"Saving features for {post_id}")
        geoj.save(f"./data/postmap/{post_id}.json")
    else:
        logger.warn(f"No features for {post_id}")
Beispiel #6
0
def stations_geojson_records():
    db = get_database_session()

    stations = get_stations(db)

    records = []

    for station in stations:

        geom = None

        if station.lat and station.lng:
            geom = Point((station.lat, station.lng))

        f = Feature(geometry=geom)

        f.properties = {
            "oid": station.oid,
            "ocode": station.ocode,
            "station_id": station.id,
            "station_code": station.network_code,
            "facility_id": station.network_code,
            "network": station.network.label,
            "network_country": station.network.country,
            "state": station.state.upper() if station.state else None,
            "postcode": station.postcode,
            "name": station.name,
            "capacity_registered": station.capacity_registered,
            "capacity_aggregate": station.capacity_aggregate,
            "duid_data": [],
        }

        for facility in station.facilities:
            if facility.fueltech_id is None:
                continue

            if facility.status_id is None:
                continue

            if duid_is_retired(facility.code):
                continue

            if facility.active is False:
                continue

            f.properties["duid_data"].append({
                "oid":
                facility.oid,
                "duid":
                facility.duid,
                "fuel_tech":
                facility.fueltech_id,
                "fuel_tech_label":
                facility.fueltech_label,
                "fuel_tech_renewable":
                facility.fueltech.renewable if facility.fueltech else None,
                "commissioned_date":
                facility.registered,
                "decommissioned_date":
                facility.deregistered,
                "status":
                facility.status_id,
                "status_label":
                facility.status_label,
                "unit_id":
                facility.unit_id,
                "unit_number":
                facility.unit_number,
                "unit_size":
                facility.unit_capacity,
                "unit_alias":
                facility.unit_alias,
                # capacities for the unit
                "capacity_registered":
                facility.capacity_registered,
                "capacity_aggregate":
                facility.capacity_aggregate,
                # network specific fields (DUID is one)
                "network_region":
                facility.network_region,
            })

        if len(f.properties["duid_data"]) > 0:
            records.append(f)

    return records
Beispiel #7
0
    for line in jsondata:
        if not line.get('country'):
            continue

        country = line['country']

        # don't need the country in the dict
        del line['country']

        #if country in data:
        #    data[country].append(line)
        #else:
        #    data[country] = [ line ]
       
        lat = float(line['lat'])
        lng = float(line['lng'])
        feature = Feature(geometry=Point((lng, lat)))

        del line['lat']
        del line['lng']

        feature.properties = line

        features.append(feature)

#except Exception as e:
#    print str(e)


with open('../data/bordercrossings/bordercrossings.geojson', 'w') as outfile:
    json.dump(FeatureCollection(features), outfile)
Beispiel #8
0
for air in (airft, airm):
    air.close()

# GeoJSON output, to KML via ogr2ogr

logger.info("Converting to GeoJSON")
fc = []

for feature in collection:
    geom = feature['geometry_ll']
    if not geom:
        logger.error("Feature without geometry: %s", feature)
        continue
    f = Feature()
    f.properties = feature['properties']
    f.properties.update({
        'fillOpacity': 0.15,
    })
    class_ = f.properties.get('class')
    from_ = int(f.properties.get('from (m amsl)'))
    to_ = int(f.properties.get('to (m amsl)'))
    if class_ in ['C', 'D', 'G', 'R']:
        if from_ < 500:
            f.properties.update({
                'fillColor': '#c04040',
                'color': '#c04040',
                'fillOpacity': 0.35
            })
        elif from_ < 1000:
            f.properties.update({'fillColor': '#c08040', 'color': '#c08040'})