Python geojson.Feature() Examples

The following are 30 code examples of geojson.Feature(). 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: meshing.py    From icepack with GNU General Public License v3.0 6 votes vote down vote up
def _flatten(features):
    r"""Expand all MultiLineString features in the input list to individual
    LineString features"""
    flat_features = []
    for feature in features:
        if feature['geometry']['type'] == 'LineString':
            flat_features.append(feature)
        if feature['geometry']['type'] == 'MultiLineString':
            properties = feature['properties']
            for line_string in feature['geometry']['coordinates']:
                geometry = geojson.LineString(coordinates=line_string)
                flat_feature = geojson.Feature(geometry=geometry,
                                               properties=properties)
                flat_features.append(flat_feature)

    return flat_features 
Example #3
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 #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: building.py    From robosat with MIT License 6 votes vote down vote up
def way(self, w):
        if not is_polygon(w):
            return

        if "building" not in w.tags:
            return

        if w.tags["building"] in self.building_filter:
            return

        if "location" in w.tags and w.tags["location"] in self.location_filter:
            return

        geometry = geojson.Polygon([[(n.lon, n.lat) for n in w.nodes]])
        shape = shapely.geometry.shape(geometry)

        if shape.is_valid:
            feature = geojson.Feature(geometry=geometry)
            self.storage.add(feature)
        else:
            print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr) 
Example #6
Source File: parking.py    From robosat with MIT License 6 votes vote down vote up
def way(self, w):
        if not is_polygon(w):
            return

        if "amenity" not in w.tags or w.tags["amenity"] != "parking":
            return

        if "parking" in w.tags:
            if w.tags["parking"] in self.parking_filter:
                return

        geometry = geojson.Polygon([[(n.lon, n.lat) for n in w.nodes]])
        shape = shapely.geometry.shape(geometry)

        if shape.is_valid:
            feature = geojson.Feature(geometry=geometry)
            self.storage.add(feature)
        else:
            print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr) 
Example #7
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_none(self):
        """Test none filter function"""
        ff = create_filter(['none', ['==', 'a', 5], ['==', 'b', 3]])
        passing = Feature(geometry=line_geometry, properties=dict(b=1))
        failing1 = Feature(geometry=line_geometry, properties=dict(a=5, b=3))
        failing2 = Feature(geometry=line_geometry, properties=dict(a=5))
        failing3 = Feature(geometry=line_geometry, properties=dict(b=3))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing1))
        self.assertFalse(ff(failing2))
        self.assertFalse(ff(failing3)) 
Example #8
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 #9
Source File: models.py    From tracker_project with MIT License 5 votes vote down vote up
def geojson_feature(self):
        return Feature(
            geometry=loads(self.location.geojson),
            id='Incident:{pk}'.format(pk=self.pk),
            properties={
                'name': self.name,
                'description': self.description,
                'severity': self.get_severity_display(),
                'created': str(self.created),
                'closed': self.closed,
                'model': 'Incident',
                'pk': self.pk,
                'url': reverse('tracker:incident-detail', kwargs={'pk': self.pk}),
            }
        ) 
Example #10
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 #11
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_comparison(self):
        """Test comparison filter function"""
        ff = create_filter(['==', 'a', 5])
        passing = Feature(geometry=line_geometry, properties=dict(a=5))
        failing = Feature(geometry=line_geometry, properties=dict(a=4))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing)) 
Example #12
Source File: S1Reader.py    From evo-odas with MIT License 5 votes vote down vote up
def get_footprint(self):
        GML_NS = "{http://www.opengis.net/gml}"
        gml_coordinates = ""
        for el in self.manifest_tree.iter(GML_NS + "coordinates"):
            gml_coordinates = el.text
        wkt_coordinates = gml_coordinates.replace(",", ";")
        wkt_coordinates = wkt_coordinates.replace(" ", ",")
        wkt_coordinates = wkt_coordinates.replace(";", " ")
        wkt_coordinates = wkt_coordinates + "," + wkt_coordinates.split(",")[0]
        s = "POLYGON ((" + wkt_coordinates + "))"
        log.info("stringa s = " + s)
        g1 = shapely.wkt.loads(s)
        g2 = geojson.Feature(geometry=g1, properties={})
        print type(g2.geometry)
        return g2.geometry 
Example #13
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_any(self):
        """Test any filter function"""
        ff = create_filter(['any', ['==', 'a', 5], ['==', 'b', 3]])
        passing1 = Feature(geometry=line_geometry, properties=dict(a=5))
        passing2 = Feature(geometry=line_geometry, properties=dict(b=3))
        passing3 = Feature(geometry=line_geometry, properties=dict(a=5, b=3))
        failing1 = Feature(geometry=line_geometry, properties=dict(a=4))
        failing2 = Feature(geometry=line_geometry, properties=dict(b=5))
        self.assertTrue(ff(passing1))
        self.assertTrue(ff(passing2))
        self.assertTrue(ff(passing3))
        self.assertFalse(ff(failing1))
        self.assertFalse(ff(failing2)) 
Example #14
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_all(self):
        """Test all filter function"""
        ff = create_filter(['all', ['==', 'a', 5], ['==', 'b', 3]])
        passing = Feature(geometry=line_geometry, properties=dict(a=5, b=3))
        failing1 = Feature(geometry=line_geometry, properties=dict(a=5))
        failing2 = Feature(geometry=line_geometry, properties=dict(b=3))
        failing3 = Feature(geometry=line_geometry, properties=dict(b=1))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing1))
        self.assertFalse(ff(failing2))
        self.assertFalse(ff(failing3)) 
Example #15
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 #16
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 #17
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_in(self):
        """Test in filter function"""
        ff = create_filter(['in', 'a', 1, 2])
        passing = Feature(geometry=line_geometry, properties=dict(a=1))
        failing = Feature(geometry=line_geometry, properties=dict(a=3))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing)) 
Example #18
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_has(self):
        """Test has filter function"""
        ff = create_filter(['has', 'a'])
        passing = Feature(geometry=line_geometry, properties=dict(a=1))
        failing = Feature(geometry=line_geometry, properties=dict(b=3))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing)) 
Example #19
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_not_has(self):
        """Test !has filter function"""
        ff = create_filter(['!has', 'a'])
        passing = Feature(geometry=line_geometry, properties=dict(b=3))
        failing = Feature(geometry=line_geometry, properties=dict(a=1))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing)) 
Example #20
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_geometry_comparison(self):
        """Test $type specific filters for comparison"""
        ff = create_filter(['==', '$type', 'Polygon'])
        # print(_compile(['==', '$type', 'Polygon']))
        passing = Feature(geometry=polygon_geometry)
        failing = Feature(geometry=line_geometry)
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing)) 
Example #21
Source File: test_filter.py    From label-maker with MIT License 5 votes vote down vote up
def test_geometry_in(self):
        """Test $type specific filters for inclusion"""
        ff = create_filter(['in', '$type', 'Point', 'Polygon'])
        # print(_compile(['in', '$type', 'Point', 'Polygon']))
        passing = Feature(geometry=polygon_geometry)
        failing = Feature(geometry=line_geometry)
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing)) 
Example #22
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 #23
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 #24
Source File: models.py    From tracker_project with MIT License 5 votes vote down vote up
def geojson_feature(self):
        return Feature(
            geometry=loads(self.polygon.geojson),
            id='AreaOfInterest:{pk}'.format(pk=self.pk),
            properties={
                'name': self.name,
                'severity': self.get_severity_display(),
                'centroid': self.polygon.centroid.geojson,
                'model': 'AreaOfInterest',
                'pk': self.pk,
                'url': reverse('tracker:area-of-interest-detail', kwargs={'pk': self.pk}),
            }
        ) 
Example #25
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 #26
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 #27
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 #28
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 #29
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 #30
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])