Python geojson.Point() Examples

The following are 13 code examples of geojson.Point(). 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: geojsonrecords.py    From open-context-py with GNU General Public License v3.0 6 votes vote down vote up
def get_recs_complex_geo_features(self, solr_recs):
        """ gets complex solr features for
            all the UUIDs in the solr records
            cuts down on the number of queries to get
            them all at once
        """
        db_geo = {}
        if self.do_complex_geo:
            uuids = []
            for solr_rec in solr_recs:
                uuids.append(solr_rec['uuid'])
            geo_data = Geospace.objects\
                               .filter(uuid__in=uuids)\
                               .exclude(ftype__in=['Point',
                                                   'point'])
            for geo in geo_data:
                if len(geo.coordinates) > 0:
                    if geo.uuid not in db_geo:
                        db_geo[geo.uuid] = geo
        # print('Number complex: ' + str(len(db_geo)))
        return db_geo 
Example #2
Source File: jsoncodec.py    From ngsi-timeseries-api with MIT License 5 votes vote down vote up
def point_to_json_rep(point: SlfPoint) -> Point:
    p = list_point_tuples(point)[0]
    return Point(p) 
Example #3
Source File: utils.py    From mapboxgl-jupyter with MIT License 5 votes vote down vote up
def row_to_geojson(row, lon, lat, precision, date_format='epoch'):
    """Convert a pandas dataframe row to a geojson format object.  Converts all datetimes to epoch seconds.
    """

    # Let pandas handle json serialization
    row_json = json.loads(row.to_json(date_format=date_format, date_unit='s'))
    return geojson.Feature(geometry=geojson.Point((round(row_json[lon], precision), round(row_json[lat], precision))),
                           properties={key: row_json[key] for key in row_json.keys() if key not in [lon, lat]}) 
Example #4
Source File: geojsonpolygons.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def get_polygon_db_objects(self, solr_polygons):
        """ processes the solr_json 
            discovery geo tiles,
            aggregating to a certain
            depth
        """
        poly_uuids = []
        for poly_key in solr_polygons[::2]:
            parsed_key = self.parse_solr_value_parts(poly_key)
            uuid = parsed_key['uuid']
            if isinstance(uuid, str):
                if uuid not in poly_uuids:
                    poly_uuids.append(uuid)
        if len(poly_uuids) > 0:
            sub_objs = Subject.objects.filter(uuid__in=poly_uuids)
            for sub_obj in sub_objs:
                uuid = sub_obj.uuid
                self.subjects_objs[uuid] = sub_obj
            exclude_types = ['Point', 'point']
            geo_objs = Geospace.objects\
                               .filter(uuid__in=poly_uuids)\
                               .exclude(ftype__in=exclude_types)
            for geo_obj in geo_objs:
                uuid = geo_obj.uuid
                
                self.geo_objs[uuid] = geo_obj 
Example #5
Source File: geojson_tools.py    From mltools with MIT License 5 votes vote down vote up
def write_to(data, property_names, output_file):
    '''
    Write list of tuples to geojson.
       First entry of each tuple should be geometry in hex coordinates
       and the rest properties.

       Args:
           data: List of tuples.
           property_names: List of strings. Should be same length as the
                           number of properties.
           output_file (str): Output file name.

    '''

    geojson_features = []
    for entry in data:
        coords_in_hex, properties = entry[0], entry[1:]
        geometry = loads(coords_in_hex, hex=True)
        property_dict = dict(zip(property_names, properties))
        if geometry.geom_type == 'Polygon':
            coords = [list(geometry.exterior.coords)]   # brackets required
            geojson_feature = geojson.Feature(geometry=geojson.Polygon(coords),
                                              properties=property_dict)
        elif geometry.geom_type == 'Point':
            coords = list(geometry.coords)[0]
            geojson_feature = geojson.Feature(geometry=geojson.Point(coords),
                                              properties=property_dict)
        geojson_features.append(geojson_feature)

    feature_collection = geojson.FeatureCollection(geojson_features)

    with open(output_file, 'wb') as f:
        geojson.dump(feature_collection, f) 
Example #6
Source File: formatter.py    From georef-ar-api with MIT License 5 votes vote down vote up
def _create_geojson_response_single(result, fmt):
    """Toma un resultado de una consulta, y devuelve una respuesta
    HTTP 200 con el resultado en formato GeoJSON.

    Args:
        result (QueryResult): Resultado de una consulta.
        fmt (dict): ParĂ¡metros de formato.

    Returns:
        flask.Response: Respuesta HTTP con contenido GeoJSON.

    """
    # Remover campos no especificados por el usuario.
    _format_result_fields(result, fmt)

    features = []
    for item in result.entities:
        lat, lon = None, None
        if N.LAT in item and N.LON in item:
            lat = item.pop(N.LAT)
            lon = item.pop(N.LON)
        elif N.CENTROID in item or N.LOCATION in item:
            loc = item.pop(N.CENTROID, None) or item.pop(N.LOCATION)
            lat = loc[N.LAT]
            lon = loc[N.LON]

        if lat and lon:
            if fmt.get(N.FLATTEN, False):
                flatten_dict(item, max_depth=3)

            point = geojson.Point((lon, lat))
            features.append(geojson.Feature(geometry=point, properties=item))

    return make_response(jsonify(geojson.FeatureCollection(features))) 
Example #7
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 #8
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 #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: web.py    From emissions-api with MIT License 4 votes vote down vote up
def get_data(session, wkt=None, distance=None, begin=None, end=None,
             limit=None, offset=None, tbl=None, **kwargs):
    """Get data in GeoJSON format.

    :param session: SQLAlchemy session
    :type session: sqlalchemy.orm.session.Session
    :param wkt: Well-known text representation of geometry, defaults to None.

    :type wkt: string, optional
    :param distance: Distance as defined in PostGIS' ST_DWithin_ function.
    :type distance: float, optional
    :type begin: datetime.datetime
    :param end: filter out points after this date
    :type end: datetime.datetime
    :param limit: Limit number of returned items
    :type limit: int
    :param offset: Specify the offset of the first item to return
    :type offset: int
    :param tbl: Table to get data from, defaults to None
    :type tbl: sqlalchemy.sql.schema.Table, optional
    :return: Feature Collection with requested Points
    :rtype: geojson.FeatureCollection

    .. _ST_DWithin: https://postgis.net/docs/ST_DWithin.html
    """
    # Init feature list
    features = []
    # Iterate through database query
    query = emissionsapi.db.get_points(session, tbl)
    # Filter result
    query = emissionsapi.db.filter_query(
        query, tbl, wkt=wkt, distance=distance, begin=begin, end=end)
    # Apply limit and offset
    query = emissionsapi.db.limit_offset_query(
        query, limit=limit, offset=offset)

    for value, timestamp, longitude, latitude in query:
        # Create and append single features.
        features.append(geojson.Feature(
            geometry=geojson.Point((longitude, latitude)),
            properties={
                "value": value,
                "timestamp": timestamp
            }))
    # Create feature collection from gathered points
    feature_collection = geojson.FeatureCollection(features)
    return feature_collection 
Example #11
Source File: make.py    From facebook-friends-map with MIT License 4 votes vote down vote up
def make_map():
    print('Geocoding locations from profiles...')
    url_base = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'

    profiles = utils.db_read(db_profiles)
    locations = utils.db_read(db_locations)
    
    geo_dict = {}
    for location in locations:
        geo_dict[location['location']] = location['coordinates']
    
    features = []
    for d in profiles:
        city = d['Current City']
        if city is not None:
            stdout.flush()
            stdout.write("\r>> Geocoding %s                         \r" % (city))
            if city in geo_dict:
                coordinates = json.loads(geo_dict[city])
            else:
                r = requests.get(url_base + city + '.json', params={
                    'access_token': mapbox_token,
                    'types': 'place,address',
                    'limit': 1
                })
                try:
                    coordinates = r.json()['features'][0]['geometry']['coordinates']
                except IndexError:
                    pass

                utils.db_write(db_locations,{'location': city,'coordinates': coordinates})
                geo_dict[city] = str(coordinates)

            features.append(Feature(
                geometry = Point(coordinates),
                properties = {'name': d['name'],'location': city,'id': d['id']}
            ))

            collection = FeatureCollection(features)
            with open(db_geojson, "w") as f:
                f.write('%s' % collection)

    with open('template-map.html') as f:
        html=f.read()
        html=html.replace('{{mapbox_token}}', mapbox_token)
        html=html.replace('{{datapoints}}', str(collection))
    with open('friends-map.html', "w", encoding="utf-8") as f:
        f.write(html)
    print('>> Saved map to friends-map.html!')
    webbrowser.open_new('file://' + os.getcwd() + '/friends-map.html') 

# Shell application 
Example #12
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 #13
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