Beispiel #1
0
def geojson_bbox(gj_object) -> Tuple[Tuple[float, float], Tuple[float, float]]:
    """
    Return bbox for a GeoJSON object as ((min_lon, min_lat), (max_lon, max_lat)).
    """
    gj = geojson.loads(json.dumps(gj_object))
    coords = []
    for feat in gj['features']:
        coords += list(geojson.coords(feat))
    coords = tuple(coords)
    bbox = min(coords), max(coords)
    return bbox
def import_geojson_to_sheet(geojson_path):
    """WARNING: will clear existing spreadsheet!!!
    pushes a geojson file to the google spreadsheet."""
    with open(geojson_path) as f:
        data = geojson.load(f)
        try:
            parsed_list = []
            for feature in data.features:
                if feature.geometry is not None \
                   and feature.geometry.type == "Point":
                    lon, lat = list(geojson.coords(feature))[0]
                    verified = feature.properties.get('Verified Status',
                                                      'unknown')
                    if (verified == 'unknown'):
                        # try to use the 'verified' field instead
                        verified = feature.properties.get(
                            'verified', 'unknown')

                    marking = feature.properties.get('Pedestrian Markings',
                                                     'unknown')
                    signal = feature.properties.get('Crossing Signal',
                                                    'unknown')
                    features = feature.properties.get('Other Features', '')
                    notes = feature.properties.get('Notes', '')
                    parsed_list.append(
                        [lon, lat, verified, marking, signal, features, notes])
            # if we got here, we built a full parsed list.
            # clear the spreadsheet and push what we have up
            try:
                worksheet = backend.worksheet("gis_dataset")
            except gspread.exceptions.WorksheetNotFound:
                worksheet = backend.add_worksheet("gis_dataset", 1, 1)
            worksheet.clear()
            row_header = [
                "Longitude", "Latitude", "Verified Status",
                "Pedestrian Markings", "Crossing Signal", "Other Features",
                "Notes"
            ]
            # create enough rows and columns to batch an update
            worksheet.resize(rows=len(parsed_list) + 1, cols=len(row_header))
            batched_cells = worksheet.range(1, 1,
                                            len(parsed_list) + 1,
                                            len(row_header))
            for cel in batched_cells:
                if cel.row == 1:
                    cel.value = row_header[cel.col - 1]
                else:
                    cel.value = parsed_list[cel.row - 2][cel.col - 1]

            worksheet.update_cells(batched_cells)
        except AttributeError as e:
            print("was expecting a file with one FeatureCollection, " +
                  "where each feature is a point!")
            print(e)
def intersect():
    try:
        data = request.get_json()
        data = data.values()
        polygons = []
        for item in data:
            coordinates = item['geometry']['coordinates']
            polygons.append(list(geojson.coords(coordinates[0])))
        polygons = [Polygon(polygon) for polygon in polygons]
        for p in range(len(polygons)):
            if polygons[0].intersection(polygons[1]):
                return 'These polygons Intersect'
        else:
            return 'These polygons don\'t intersect'
    except:
        return 'Please enter valid geoJSON Object'
Beispiel #4
0
def ogr2df(ogr_data, table=None, clean=True):
    """Converts geojson to pandas dataframe.
    Args:
        json_features (dict, or geojson.FeatureCollection): input geojson
        clean (bool): drops extra spatial ref fields and cleans names (True)
        rename_geom (bool): renames 'coordinates' field to 'geometry'
    Returns pandas.DataFrame.
    """
    # Convert ogr input to geojson
    json_features = ogr2geojson(ogr_data, table)

    # Convert geojson.FeatureCollection to pandas.DataFrame
    dataframes = []
    for feature in json_features["features"]:
        geom = unicode(geojson.dumps(feature["geometry"]))
        normalized = json_normalize(feature)  # json.loads(feature))
        normalized["srid"] = json_normalize(json_features["crs"])["properties.name"].ix[0].split(":")[1]
        df_feature = pd.DataFrame(normalized)
        df_feature["geometry.coordinates"] = geom
        dataframes.append(df_feature)
    df = pd.concat(dataframes).reset_index("id", drop=True)

    # Geom info
    df["srid"] = df["srid"].astype(numpy.int32)
    df["shape_type"] = df["geometry.type"].astype(str)
    # Check Z dimension of first row -- assume all dims are the same
    ndims = max([len(coord) for coord in geojson.coords(geojson.loads(df["geometry.coordinates"].ix[0]))])
    all_dims = "XYZM"
    df["dims"] = all_dims[:ndims]

    if not clean:
        return df

    df.drop(["geometry.type", "type"], 1, inplace=True)
    columns = [re.sub("properties.|geometry.", "", col) for col in df.columns]
    df.columns = columns

    # Push 'coordinates' column to end (2nd last); 'srid' last
    cols = df.columns.tolist()
    cols.insert(len(cols), cols.pop(cols.index("coordinates")))
    cols.insert(len(cols), cols.pop(cols.index("srid")))
    df = df[cols]

    # Clean nan and None to unicode("None")
    df = df.applymap(lambda x: "None" if x is None or x is numpy.nan else x)
    return df
Beispiel #5
0
def ogr2df(ogr_data, table="", reproject_srid="", clean=True):
    """Converts geojson to pandas dataframe.
    Args:
        json_features (dict, or geojson.FeatureCollection): input geojson
        clean (bool): drops extra spatial ref fields and cleans names (True)
        rename_geom (bool): renames 'coordinates' field to 'geometry'
    Returns pandas.DataFrame.
    """
    # Convert ogr input to geojson
    if not ogr_data.endswith(".json"):
        tmp = "temp.json"
        json_features = geojson.load(open(
            ogr2json(ogr_data, table, tmp, reproject_srid=reproject_srid))) #ogr2geojson(ogr_data, table)
        os.unlink(tmp)
    else:
        with open(ogr_data) as f:
            json_features = geojson.load(f)

    # Convert geojson.FeatureCollection to pandas.DataFrame
    dataframes = []
    for feature in json_features["features"]:
        geom = unicode(geojson.dumps(feature["geometry"]))
        normalized = json_normalize(feature)  # json.loads(feature))
        try:
            normal_crs = json_normalize(
                json_features["crs"])["properties.name"].ix[0]
        except KeyError:
            raise IOError("Input json does not have valid spatial reference")
        if "::" in normal_crs:
            colon = "::"
        else:
            colon = ":"
        normalized["srid"] = normal_crs.split(colon)[1]
        df_feature = pd.DataFrame(normalized)
        df_feature['geometry.coordinates'] = geom
        dataframes.append(df_feature)
    df = pd.concat(dataframes).reset_index("id", drop=True)

    # Geom info
    df['srid'] = df['srid'].astype(numpy.int32)
    df["shape_type"] = df["geometry.type"].astype(str)
    # Check Z dimension of first row -- assume all dims are the same
    ndims = max([len(coord) for coord in geojson.coords(
        geojson.loads(df["geometry.coordinates"].ix[0]))])
    all_dims = "XYZM"
    df["dims"] = all_dims[:ndims]

    if not clean:
        return df

    df.drop(['geometry.type', 'type'], 1,
            inplace=True)
    columns = [re.sub("properties.|geometry.", "", col)
               for col in df.columns]
    df.columns = columns

    # Push 'coordinates' column to end (2nd last); 'srid' last
    cols = df.columns.tolist()
    cols.insert(len(cols), cols.pop(cols.index("coordinates")))
    cols.insert(len(cols), cols.pop(cols.index("srid")))
    df = df[cols]

    # Clean nan and None to unicode("None")
    df = df.applymap(lambda x: u"None" if x is None or x is numpy.nan else x)
    return df
Beispiel #6
0
def get_point_from_feature(feature):
    coords, = [x for x in geojson.coords(feature)]
    lon, lat = coords  # geoJSON uses reverse order
    point = Point(lat, lon)
    return point