Python geojson.dumps() Examples

The following are 12 code examples of geojson.dumps(). 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: api.py    From jacs with Apache License 2.0 6 votes vote down vote up
def do_features_list(table):
    """Handle the parsing of the request and return the geojson.

    This routes all the /tables/... requests to the handler.
    See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route

    Args:
      database: The name of the database to use, this is picked from the URL.
      table: The database table to query from, this is picked from the URL.
    Returns:
      A flask.Response object with the GeoJSON to be returned, or an error JSON.
    """
    where = flask.request.args.get('where', default='true')
    select = flask.request.args.get('select', default='')
    limit = flask.request.args.get('limit')
    order_by = flask.request.args.get('orderBy')
    intersects = flask.request.args.get('intersects')
    offset = flask.request.args.get('offset')

    result = flask.g.features.list(table, select, where,
        limit=limit, offset=offset, order_by=order_by,
        intersects=intersects)

    return build_response(result, geojson.dumps) 
Example #2
Source File: contour.py    From geojsoncontour with MIT License 5 votes vote down vote up
def _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize):
    if not serialize:
        return feature_collection
    if strdump or not geojson_filepath:
        return geojson.dumps(feature_collection, sort_keys=True, separators=(',', ':'))
    with open(geojson_filepath, 'w') as fileout:
        geojson.dump(feature_collection, fileout, sort_keys=True, separators=(',', ':')) 
Example #3
Source File: jsoncodec.py    From ngsi-timeseries-api with MIT License 5 votes vote down vote up
def encode(geom: SlfGeometry) -> Optional[str]:
    """
    Convert the given Simple Location Format shape to the corresponding
    GeoJSON shape.

    :param geom: the Simple Location Format shape to convert.
    :return: the GeoJSON as a string if the input shape is of a known type;
        ``None`` otherwise.
    """
    geo_json_rep = lookup_encoder(geom)(geom)
    if geo_json_rep:
        return dumps(geo_json_rep, sort_keys=True)
    return None 
Example #4
Source File: dataset_utility.py    From minerva with Apache License 2.0 5 votes vote down vote up
def __init__(self, objConverter, header='[', footer=']',
                 jsonDumpser=json.dumps):
        self.objConverter = objConverter
        self.header = header
        self.footer = footer
        self.jsonDumpser = json.dumps 
Example #5
Source File: api.py    From jacs with Apache License 2.0 5 votes vote down vote up
def build_response(result, method=json.dumps):
    status = 200
    if 'status' in result:
        status = result['status']
    if 'error' in result:
        method = json.dumps
        if status is None:
            status = 500
    return flask.Response(
            response=method(result),
            mimetype='application/json',
            status = status) 
Example #6
Source File: api.py    From jacs with Apache License 2.0 5 votes vote down vote up
def do_pip(database, table):
    """Handle the parsing of the point in polygon request and return a polygon.

    This routes all the /pip/... requests to the handler.
    See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route

    Args:
      database: The name of the database to use, this is picked from the URL.
      table: The database table to query from, this is picked from the URL.
    Returns:
      A flask.Response object with the GeoJSON to be returned, or an error JSON.
    """
    lat = float(flask.request.args.get('lat', default=0.0))
    lng = float(flask.request.args.get('lng', default=0.0))
    select = flask.request.args.get('select', default='')
    try:
        pip = PointInPolygon(_INSTANCE, database, table)
    except MySQLdb.OperationalError as e:
        error = {'error': 'Database Error %s' % str(e)}
    return flask.Response(
            response=json.dumps(error),
            mimetype='application/json',
            status=500)

    polygon = pip.pip(lat, lng, select)
    if 'error' in polygon:
        return flask.Response(
            response=json.dumps(polygon),
            mimetype='application/json',
            status=500)
    else:
        return flask.Response(
            response=geojson.dumps(polygon, sort_keys=True),
            mimetype='application/json',
            status=200) 
Example #7
Source File: vissim_to_geojson.py    From vissim with MIT License 5 votes vote down vote up
def export(self, filename):
        """ Export GeoJSON object to file
            Input: filename
            Output: written file
        """
        f = open(filename, 'w')
        f.writelines(geojson.dumps(self.geojson))
        f.close() 
Example #8
Source File: swmm_graphics.py    From swmmio with MIT License 5 votes vote down vote up
def create_map(model=None, filename=None):
    """
    export model as a geojson object
    """

    import geojson
    if filename is None:
        filename = f'{model.name}.html'

    if model.crs:
        model.to_crs("+init=EPSG:4326")
    else:
        raise ValueError('Model object must have a valid crs')

    # get map centroid and bbox
    c, bbox = centroid_and_bbox_from_coords(model.inp.coordinates)

    # start writing that thing
    with open(BETTER_BASEMAP_PATH, 'r') as bm:
        with open(filename, 'w') as newmap:
            for line in bm:
                if 'INSERT GEOJSON HERE' in line:
                    newmap.write(f'conduits = {geojson.dumps(model.links.geojson)}\n')
                    newmap.write(f'nodes = {geojson.dumps(model.nodes.geojson)}\n')
                elif '// INSERT MAP CENTER HERE' in line:
                    newmap.write('\tcenter:[{}, {}],\n'.format(c[0], c[1]))
                elif '// INSERT BBOX HERE' in line and bbox is not None:
                    newmap.write('\tmap.fitBounds([[{}, {}], [{}, {}]]);\n'
                                 .format(bbox[0], bbox[1], bbox[2],
                                         bbox[3]))
                else:
                    newmap.write(line) 
Example #9
Source File: dataset_utility.py    From minerva with Apache License 2.0 4 votes vote down vote up
def __init__(self, objConverter=None, mapping=None):
        geojson_header = """{
        "type": "FeatureCollection",
        "crs": {
            "type": "name",
            "properties": {
                "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        "features": [
        """

        geojson_footer = """
        ]
        }
        """

        if objConverter is None:
            if mapping is None:
                raise Exception('Must provide objConverter or geoJsonMapping')

            def convertToGeoJson(obj):
                lat_expr = jsonpath_rw.parse(mapping['latitudeKeypath'])
                long_expr = jsonpath_rw.parse(mapping['longitudeKeypath'])

                def extractLat(obj):
                    match = lat_expr.find(obj)
                    return float(match[0].value)

                def extractLong(obj):
                    match = long_expr.find(obj)
                    return float(match[0].value)

                point = geojson.Point((extractLong(obj), extractLat(obj)))
                properties = {"placeholder": 0}
                feature = geojson.Feature(geometry=point,
                                          properties=properties)
                return feature

            objConverter = convertToGeoJson

        super(GeoJsonMapper, self).__init__(objConverter, geojson_header,
                                            geojson_footer, geojson.dumps) 
Example #10
Source File: utils.py    From mapboxgl-jupyter with MIT License 4 votes vote down vote up
def df_to_geojson(df, properties=None, lat='lat', lon='lon', precision=6, date_format='epoch', filename=None):
    """Serialize a Pandas dataframe to a geojson format Python dictionary / file
    """

    if not properties:
        # if no properties are selected, use all properties in dataframe
        properties = [c for c in df.columns if c not in [lon, lat]]

    for prop in properties:
        # Check if list of properties exists in dataframe columns
        if prop not in list(df.columns):
            raise ValueError(
                'properties must be a valid list of column names from dataframe')
        if prop in [lon, lat]:
            raise ValueError(
                'properties cannot be the geometry longitude or latitude column')

    # convert dates/datetimes to preferred string format if specified
    df = convert_date_columns(df, date_format)

    if filename:
        with open(filename, 'w') as f:
            # Overwrite file if it already exists
            pass

        with open(filename, 'a+') as f:

            # Write out file to line
            f.write('{"type": "FeatureCollection", "features": [\n')
            # Iterate over enumerated iterrows as index from iterrows alone could be non-sequential
            for i, (index, row) in enumerate(df[[lon, lat] + properties].iterrows()):
                if i == 0:
                    f.write(geojson.dumps(row_to_geojson(row, lon, lat, precision, date_format)) + '\n')
                else:
                    f.write(',' + geojson.dumps(row_to_geojson(row, lon, lat, precision, date_format)) + '\n')
            f.write(']}')

            return {
                "type": "file",
                "filename": filename,
                "feature_count": df.shape[0]
            }
    else:
        features = []
        df[[lon, lat] + properties].apply(lambda x: features.append(
            row_to_geojson(x, lon, lat, precision, date_format)), axis=1)
        return geojson.FeatureCollection(features) 
Example #11
Source File: getdatafromosm.py    From images-to-osm with MIT License 4 votes vote down vote up
def saveOsmData(query) :

    result = api.query(query)

    for way in result.ways:

        # "leisure=pitch,sport=" , don't use "-" char" in featureDirectoryName
        featureDirectoryName = way.tags.get("sport")

        outputDirectoryName = os.path.join(cfg.rootOsmDir,featureDirectoryName)
        if ( os.path.exists(outputDirectoryName) == False):
            os.makedirs(outputDirectoryName)

        if ( (featureDirectoryName in summary) == False) :
            summary[featureDirectoryName]  = 1
        else:     
            summary[featureDirectoryName] += 1
        
        filenameBase= os.path.join(cfg.rootOsmDir,featureDirectoryName,str(way.id))

        #print("Name: %d %s %s" % ( way.id ,way.tags.get("name", ""),filenameBase))

        # leave the csv file for now, will delete when the script for the next
        # stage is rewritten.
        with open("%s.csv" % (filenameBase), "wt") as text_file:
            for node in way.nodes:
                text_file.write("%0.7f\t%0.7f\n" % (node.lat, node.lon))

        with open("%s.GeoJSON" % (filenameBase), "wt") as text_file:

            rawNodes = []
            for node in way.nodes:
                rawNodes.append( (node.lon, node.lat) )
            
            try:
                geom = shapely.geometry.Polygon(rawNodes)

                tags = way.tags
                tags['wayOSMId'] = way.id

                features =[]            
                features.append( geojson.Feature(geometry=geom, properties=tags))

                featureC = geojson.FeatureCollection(features)

                text_file.write(geojson.dumps(featureC))
            except Exception as e:
                print(e) 
Example #12
Source File: reporting.py    From swmmio with MIT License 4 votes vote down vote up
def write(self, rpt_dir):
        #write cost per sewer segment spreadsheet
        self.newconduits.to_csv(os.path.join(rpt_dir,'cost_estimate.csv'))
        self.flood_comparison.to_csv(os.path.join(rpt_dir,'parcel_flood_comparison.csv'))

        #write parcel json files
        parcels = spatial.read_shapefile(sg.config.parcels_shapefile)
        parcels = parcels[['PARCELID', 'ADDRESS', 'OWNER1', 'coords']]
        flooded = self.flood_comparison
        flooded = flooded.loc[flooded.Category.notnull()] #parcels with significant flood delta
        flooded = pd.merge(flooded, parcels, right_on='PARCELID', left_index=True)
        colors = flooded.apply(lambda row:'#%02x%02x%02x' % drawing.parcel_draw_color(row, style='delta'), axis=1)
        flooded = flooded.assign(fill=colors)
        geoparcelpath = os.path.join(rpt_dir,'delta_parcels.json')
        spatial.write_geojson(flooded, filename=geoparcelpath, geomtype='polygon')

        #write new conduit json, shapefiles
        shpdir = os.path.join(os.path.dirname(rpt_dir), 'shapefiles')
        if not os.path.exists(shpdir):os.mkdir(shpdir)
        geocondpath = os.path.join(rpt_dir,'new_conduits.json')
        shpcondpath = os.path.join(shpdir, self.alt_report.model.inp.name + '_new_conduits.shp')
        spatial.write_geojson(self.newconduits, filename=geocondpath)
        spatial.write_shapefile(self.newconduits, filename=shpcondpath)

        #write node and conduit report csvs
        self.alt_report.model.nodes().to_csv(os.path.join(rpt_dir,'nodes.csv'))
        self.alt_report.model.conduits().to_csv(os.path.join(rpt_dir,'conduits.csv'))

        #write a html map
        with open (geocondpath, 'r') as f:
            geo_conduits = geojson.loads(f.read())


        proposed_flooded = self.alt_report.parcel_flooding
        proposed_flooded = pd.merge(proposed_flooded, parcels, right_on='PARCELID', left_index=True)
        geo_parcels = spatial.write_geojson(proposed_flooded)
        # with open (geoparcelpath, 'r') as f:
        #     geo_parcels = geojson.loads(f.read())

        with open(BETTER_BASEMAP_PATH, 'r') as bm:
            filename = os.path.join(os.path.dirname(geocondpath), self.alt_report.model.name + '.html')
            with open(filename, 'wb') as newmap:
                for line in bm:
                    if '//INSERT GEOJSON HERE ~~~~~' in line:
                        newmap.write('conduits = {};\n'.format(geojson.dumps(geo_conduits)))
                        newmap.write('nodes = {};\n'.format(0))
                        newmap.write('parcels = {};\n'.format(geojson.dumps(geo_parcels)))
                    else:
                        newmap.write(line)


        #create figures