Python geojson.FeatureCollection() Examples

The following are 30 code examples of geojson.FeatureCollection(). 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: vissim_to_geojson.py    From vissim with MIT License 6 votes vote down vote up
def createGeoJSON(self):
        """ Get list of link geometries and properties to be converted.
            Input: Vissim object
            Output: list of links
        """
        features = []
        for link in self.data.xpath('./links/link'):
            geos = []
            linkNum = link.attrib['no']
            for geo in link.xpath('./geometry/points3D/point3D'):
                x, y = geo.attrib['x'], geo.attrib['y']
                latLng = self.scaledMetersToNode((x, y))
                geos.append(latLng)
            linkNum = link.attrib['no']
            laneNum = str(len(link.xpath('./lanes/lane')))
            multiLine = geojson.MultiLineString(coordinates=geos)
            features.append(geojson.Feature(id=linkNum, geometry=multiLine,
                                            properties={'lane': laneNum,
                                                        'id': linkNum}))
        return geojson.FeatureCollection(features) 
Example #2
Source File: views.py    From indrz with GNU General Public License v3.0 6 votes vote down vote up
def force_route_mid_point(request, **kwargs):
    """
    Force a route over a middle point such as a front office
    :return: a single GeoJSON featureCollection with a middle point
    :param
    """
    start_node = request.GET.get('startnode', 1)  # 1385
    mnode = request.GET.get('midnode', 1)  # 1167
    end_node = request.GET.get('endnode', 1)  # 1252

    # building_id = 1
    route_nodes = {'building-id': 1, 'start-node-id': start_node, 'mid-node-id': mnode, 'end-node-id': end_node}

    # remove last coordinate of first route
    start_node_id = get_room_centroid_node(route_nodes['start-node-id'])
    mid_node_id = get_room_centroid_node(route_nodes['mid-node-id'])
    end_node_id = get_room_centroid_node(route_nodes['end-node-id'])

    route_start_to_mid_point = run_route(start_node_id, mid_node_id, 1)
    route_mid_to_end_point = run_route(mid_node_id, end_node_id, 1)

    route_out_merge = merge_2_routes(route_start_to_mid_point, route_mid_to_end_point)

    return Response({'type': 'FeatureCollection', 'features': route_out_merge}) 
Example #3
Source File: geojson_tools.py    From mltools with MIT License 6 votes vote down vote up
def split(input_file, file_1, file_2, no_in_first_file):
    '''
    Split a geojson in two separate files.

       Args:
           input_file (str): Input filename.
           file_1 (str): Output file name 1.
           file_2 (str): Output file name 2.
           no_features (int): Number of features in input_file to go to file_1.
           output_file (str): Output file name.
    '''

    # get feature collection
    with open(input_file) as f:
        feat_collection = geojson.load(f)

    features = feat_collection['features']
    feat_collection_1 = geojson.FeatureCollection(features[0:no_in_first_file])
    feat_collection_2 = geojson.FeatureCollection(features[no_in_first_file:])

    with open(file_1, 'w') as f:
        geojson.dump(feat_collection_1, f)

    with open(file_2, 'w') as f:
        geojson.dump(feat_collection_2, f) 
Example #4
Source File: sentinel.py    From sentinelsat with GNU General Public License v3.0 6 votes vote down vote up
def to_geojson(products):
        """Return the products from a query response as a GeoJSON with the values in their
        appropriate Python types.
        """
        feature_list = []
        for i, (product_id, props) in enumerate(products.items()):
            props = props.copy()
            props["id"] = product_id
            poly = geomet.wkt.loads(props["footprint"])
            del props["footprint"]
            del props["gmlfootprint"]
            # Fix "'datetime' is not JSON serializable"
            for k, v in props.items():
                if isinstance(v, (date, datetime)):
                    props[k] = v.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
            feature_list.append(geojson.Feature(geometry=poly, id=i, properties=props))
        return geojson.FeatureCollection(feature_list) 
Example #5
Source File: geocoder.py    From minerva with Apache License 2.0 6 votes vote down vote up
def createGeojson(geocoder, locations):
        """Create geojson for given locations and geocoder url"""

        geoms = []

        for i in locations:
            wkt = Geocoder.getWktFromGeocoder(geocoder, i)
            geom = Geocoder.createGeometryFromWkt(wkt)
            try:
                for g in geom:
                    geoms.append(geojson.Feature(geometry=g,
                                                 properties={'location': i}))
            except TypeError:
                geoms.append(geojson.Feature(geometry=geom,
                                             properties={'location': i}))
        multiPoly = geojson.FeatureCollection(geoms)

        return multiPoly 
Example #6
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 #7
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 #8
Source File: views.py    From indrz with GNU General Public License v3.0 5 votes vote down vote up
def get_features(FeatureCollection):
    props_list = []
    for feature in FeatureCollection:
        props_list.append(feature['properties'])

    return props_list 
Example #9
Source File: extract_mgrs_tile_coordinates_from_kml.py    From tsd with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(kml_filename, verbose=False):
    """
    Extract information from the kml file distributed by ESA to describe the
    Sentinel-2 MGRS tiling grid.

    This file is distributed on ESA Sentinel website at:

    https://sentinel.esa.int/documents/247904/1955685/S2A_OPER_GIP_TILPAR_MPC__20151209T095117_V20150622T000000_21000101T000000_B00.kml
    """
    kml2geojson.main.convert(kml_filename, 's2_mgrs_grid')
    with open(os.path.join('s2_mgrs_grid', kml_filename.replace('.kml', '.geojson')), 'r') as f:
        grid = geojson.load(f)

    mgrs_tiles = []
    for x in grid['features']:
        g = x['geometry']
        keep_only_polygons_from_geometry_collection(g)
        for p in g['geometries']:
            remove_z_from_polygon_coordinates(p)
        mgrs_id = x['properties']['name']
        mgrs_tiles.append(geojson.Feature(id=mgrs_id, geometry=g))
        if verbose:
            print(mgrs_id, end=' ')
            print(g)

    return geojson.FeatureCollection(mgrs_tiles) 
Example #10
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 #11
Source File: __init__.py    From ml-enabler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def validate_geojson(data):
    """
    Validate geojson
    """

    if not (isinstance(data, dict)):
        return False

    if not isinstance(data.get('features'), list):
        return False

    gj = geojson.FeatureCollection([geojson.Feature(f) for f in data['features']])
    return gj.is_valid 
Example #12
Source File: views.py    From tracker_project with MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        features = [incident.geojson_feature for incident in Incident.objects.filter(closed=False)]
        feature_collection = FeatureCollection(features)

        return self.render_json_response(feature_collection) 
Example #13
Source File: meshing_test.py    From icepack with GNU General Public License v3.0 5 votes vote down vote up
def needs_reorienting():
    coords = [[(0., 0.), (1., 0.), (1., 1.)],
              [(0., 0.), (0., 1.), (1., 1.)]]
    multi_line_string = geojson.MultiLineString(coords, validate=True)
    feature = geojson.Feature(geometry=multi_line_string, properties={})
    return geojson.FeatureCollection([feature]) 
Example #14
Source File: meshing_test.py    From icepack with GNU General Public License v3.0 5 votes vote down vote up
def needs_snapping():
    coords = [[(0., -1e-6), (1., 0.), (1., 1. - 1e-6)],
              [(1., 1. + 1e-6), (0., 1.), (0., 1e-6)]]
    multi_line_string = geojson.MultiLineString(coords, validate=True)
    feature = geojson.Feature(geometry=multi_line_string, properties={})
    return geojson.FeatureCollection([feature]) 
Example #15
Source File: export.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def campaign_visits_to_geojson(rpc, campaign_id, geojson_file):
	"""
	Export the geo location information for all the visits of a campaign into
	the `GeoJSON <http://geojson.org/>`_ format.

	:param rpc: The connected RPC instance to load the information with.
	:type rpc: :py:class:`.KingPhisherRPCClient`
	:param campaign_id: The ID of the campaign to load the information for.
	:param str geojson_file: The destination file for the GeoJSON data.
	"""
	ips_for_georesolution = {}
	ip_counter = collections.Counter()
	for visit_node in _get_graphql_campaign_visits(rpc, campaign_id):
		visit = visit_node['node']
		ip_counter.update((visit['ip'],))
		visitor_ip = ipaddress.ip_address(visit['ip'])
		if not isinstance(visitor_ip, ipaddress.IPv4Address):
			continue
		if visitor_ip.is_loopback or visitor_ip.is_private:
			continue
		if not visitor_ip in ips_for_georesolution:
			ips_for_georesolution[visitor_ip] = visit['firstSeen']
		elif ips_for_georesolution[visitor_ip] > visit['firstSeen']:
			ips_for_georesolution[visitor_ip] = visit['firstSeen']
	ips_for_georesolution = [ip for (ip, _) in sorted(ips_for_georesolution.items(), key=lambda x: x[1])]
	locations = {}
	for ip_addresses in iterutils.chunked(ips_for_georesolution, 50):
		locations.update(rpc.geoip_lookup_multi(ip_addresses))
	points = []
	for ip, location in locations.items():
		if not (location.coordinates and location.coordinates[0] and location.coordinates[1]):
			continue
		points.append(geojson.Feature(geometry=location, properties={'count': ip_counter[ip], 'ip-address': ip}))
	feature_collection = geojson.FeatureCollection(points)
	with open(geojson_file, 'w') as file_h:
		serializers.JSON.dump(feature_collection, file_h, pretty=True) 
Example #16
Source File: views.py    From tracker_project with MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        features = [
            area_of_interest.geojson_feature for area_of_interest in AreaOfInterest.objects.all()
        ]
        feature_collection = FeatureCollection(features)

        return self.render_json_response(feature_collection) 
Example #17
Source File: parking.py    From robosat with MIT License 5 votes vote down vote up
def save(self, out):
        collection = geojson.FeatureCollection(self.features)

        with open(out, "w") as fp:
            geojson.dump(collection, fp) 
Example #18
Source File: core.py    From robosat with MIT License 5 votes vote down vote up
def flush(self):
        if not self.features:
            return

        collection = geojson.FeatureCollection(self.features)

        base, ext = os.path.splitext(self.out)
        suffix = uuid.uuid4().hex

        out = "{}-{}{}".format(base, suffix, ext)

        with open(out, "w") as fp:
            geojson.dump(collection, fp)

        self.features.clear() 
Example #19
Source File: dataset.py    From minerva with Apache License 2.0 5 votes vote down vote up
def unwrapFeature(geometry):
    if geometry.type == 'FeatureCollection':
        geometries = [n.geometry for n in geometry.features]
        return geojson.GeometryCollection(geometries)
    elif geometry.type == 'Feature':
        return geometry.geometry
    else:
        return geometry 
Example #20
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 #21
Source File: contour.py    From geojsoncontour with MIT License 5 votes vote down vote up
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None,
                                ndigits=5, unit='', stroke_width=1, fill_opacity=.9,
                                geojson_properties=None, strdump=False, serialize=True):
    """Transform matplotlib.contourf to geojson with overlapping filled contours."""
    polygon_features = []
    contourf_idx = 0
    contourf_levels = get_contourf_levels(contourf.levels, contourf.extend)
    for collection in contourf.collections:
        color = collection.get_facecolor()
        for path in collection.get_paths():
            for coord in path.to_polygons():
                if min_angle_deg:
                    coord = keep_high_angle(coord, min_angle_deg)
                coord = np.around(coord, ndigits) if ndigits else coord
                polygon = Polygon(coordinates=[coord.tolist()])
                fcolor = rgb2hex(color[0])
                properties = set_contourf_properties(stroke_width, fcolor, fill_opacity, contourf_levels[contourf_idx], unit)
                if geojson_properties:
                    properties.update(geojson_properties)
                feature = Feature(geometry=polygon, properties=properties)
                polygon_features.append(feature)
        contourf_idx += 1
    feature_collection = FeatureCollection(polygon_features)
    return _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize) 
Example #22
Source File: contour.py    From geojsoncontour with MIT License 5 votes vote down vote up
def contourf_to_geojson(contourf, geojson_filepath=None, min_angle_deg=None,
                        ndigits=5, unit='', stroke_width=1, fill_opacity=.9, fill_opacity_range=None,
                        geojson_properties=None, strdump=False, serialize=True):
    """Transform matplotlib.contourf to geojson with MultiPolygons."""
    if fill_opacity_range:
        variable_opacity = True
        min_opacity, max_opacity = fill_opacity_range
        opacity_increment = (max_opacity - min_opacity) / len(contourf.levels)
        fill_opacity = min_opacity
    else:
        variable_opacity = False
    polygon_features = []
    contourf_levels = get_contourf_levels(contourf.levels, contourf.extend)
    for coll, level in zip(contourf.collections, contourf_levels):
        color = coll.get_facecolor()
        muli = MP(coll, min_angle_deg, ndigits)
        polygon = muli.mpoly()
        fcolor = rgb2hex(color[0])
        properties = set_contourf_properties(stroke_width, fcolor, fill_opacity, level, unit)
        if geojson_properties:
            properties.update(geojson_properties)
        feature = Feature(geometry=polygon, properties=properties)
        polygon_features.append(feature)
        if variable_opacity:
            fill_opacity += opacity_increment
    feature_collection = FeatureCollection(polygon_features)
    return _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize) 
Example #23
Source File: dataset.py    From minerva with Apache License 2.0 5 votes vote down vote up
def linkAndAssembleGeometry(self, link, linkItemId, records):
        try:
            item = self.model('item').load(linkItemId, force=True)
            featureCollections = self.downloadDataset(item)
        except Exception:
            raise GirderException('Unable to load link target dataset.')

        valueLinks = sorted([x for x in link
                             if x['operator'] == '='])
        constantLinks = [x for x in link
                         if x['operator'] == 'constant']
        mappedGeometries = {}
        linkingDuplicateCount = 0
        for feature in featureCollections['features']:
            skipCurrentFeature = False
            for constantLink in constantLinks:
                if feature['properties'][constantLink['field']] != constantLink['value']:
                    # If the feature dones't satisfy any constant linking condition
                    skipCurrentFeature = True
                    break
            if skipCurrentFeature:
                continue
            try:
                key = ''.join([str(feature['properties'][x['field']]) for x in valueLinks])
            except KeyError:
                raise GirderException('missing property for key ' +
                                      x['field'] + ' in geometry link target geojson')
            if key in mappedGeometries:
                linkingDuplicateCount += 1
            mappedGeometries[key] = feature['geometry']

        assembled = []
        for record in records:
            key = ''.join([str(record[x['value']]) for x in valueLinks])
            if key in mappedGeometries:
                assembled.append(
                    geojson.Feature(geometry=mappedGeometries[key], properties=record)
                )
        return geojson.FeatureCollection(assembled), linkingDuplicateCount 
Example #24
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 #25
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 #26
Source File: query_builder.py    From openpoiservice with Apache License 2.0 4 votes vote down vote up
def generate_geojson_features(cls, query, limit):
        """
        Generates a GeoJSON feature collection from the response.
        :param limit:
        :param query: the response from the database
        :type query: list of objects
        :return: GeoJSON feature collection containing properties
        :type: list
        """

        geojson_features = []
        lat_lngs = []

        for q_idx, q in enumerate(query):

            geometry = wkb.loads(str(q[3]), hex=True)
            x = float(format(geometry.x, ".6f"))
            y = float(format(geometry.y, ".6f"))
            trimmed_point = Point(x, y)

            lat_lngs.append((trimmed_point.x, trimmed_point.y))

            properties = dict(
                osm_id=int(q[0]),
                osm_type=int(q[1]),
                distance=float(q[2])
            )

            category_ids_obj = {}
            for c_id in set(q[6]):
                category_name = categories_tools.category_ids_index[c_id]['poi_name']
                category_group = categories_tools.category_ids_index[c_id]['poi_group']
                category_ids_obj[c_id] = {
                    "category_name": category_name,
                    "category_group": category_group
                }
            properties["category_ids"] = category_ids_obj

            if q[5][0] is not None:
                key_values = {}
                for idx, key in enumerate(q[4]):
                    key_values[key] = q[5][idx]
                properties["osm_tags"] = key_values

            geojson_feature = geojson.Feature(geometry=trimmed_point,
                                              properties=properties)
            geojson_features.append(geojson_feature)

            # limit reached
            if q_idx == limit - 2:
                break

        feature_collection = geojson.FeatureCollection(geojson_features, bbox=MultiPoint(lat_lngs).bounds)

        logger.info("Amount of features {}".format(len(geojson_features)))

        return feature_collection 
Example #27
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 #28
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 #29
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 #30
Source File: quadtree.py    From kite with GNU General Public License v3.0 4 votes vote down vote up
def export_geojson(self, filename):
        import geojson
        self._log.debug('Exporting GeoJSON Quadtree to %s', filename)
        features = []

        for lf in self.leaves:
            llN, llE, urN, urE = (lf.llN, lf.llE, lf.urN, lf.urE)

            if self.frame.isDegree():
                llN += self.frame.llLat
                llE += self.frame.llLon
                urN += self.frame.llLat
                urE += self.frame.llLon

            coords = num.array([
                (llN, llE),
                (llN, urE),
                (urN, urE),
                (urN, llE),
                (llN, llE)])

            if self.frame.isMeter():
                coords = od.ne_to_latlon(
                    self.frame.llLat, self.frame.llLon, *coords.T)
                coords = num.array(coords).T

            coords = coords[:, [1, 0]].tolist()

            feature = geojson.Feature(
                geometry=geojson.Polygon(coordinates=[coords]),
                id=lf.id,
                properties={
                    'mean': float(lf.mean),
                    'median': float(lf.median),
                    'std': float(lf.std),
                    'var': float(lf.var),

                    'phi': float(lf.phi),
                    'theta': float(lf.theta),
                    'unitE': float(lf.unitE),
                    'unitN': float(lf.unitN),
                    'unitU': float(lf.unitU),
                })
            features.append(feature)

        collection = geojson.FeatureCollection(
            features)
        with open(filename, 'w') as f:
            geojson.dump(collection, f)