Python geojson.dump() Examples

The following are 15 code examples of geojson.dump(). 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: geojson_tools.py    From mltools with MIT License 6 votes vote down vote up
def join(input_files, output_file):
    '''
    Join geojsons into one. The spatial reference system of the
       output file is the same as the one of the last file in the list.

       Args:
           input_files (list): List of file name strings.
           output_file (str): Output file name.
    '''

    # get feature collections
    final_features = []
    for file in input_files:
        with open(file) as f:
            feat_collection = geojson.load(f)
            final_features += feat_collection['features']

    feat_collection['features'] = final_features

    # write to output file
    with open(output_file, 'w') as f:
        geojson.dump(feat_collection, f) 
Example #2
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 #3
Source File: bus_router.py    From bus-router with MIT License 6 votes vote down vote up
def osrmDirectionsCall(stop, origin, dest, osrmpoints, fname):
	print "getting dirs..."
	base = 'http://router.project-osrm.org/viaroute?'
	viastring = ""
	for point in osrmpoints:
		viastring += 'loc=' + point + '&'

	params = 'loc=' + origin + '&' + viastring + 'loc=' + dest
	# params = urllib.urlencode({'loc': origin, 'loc': dest, 'waypoints': waypoints, 'sensor': 'false','key': google_key})
	print params
	# if waypoints == "":
	with open("log.txt", 'a') as log:
		log.write(base + params + '\n')
	response = urllib.urlopen(base + params)
	data = json.load(response)
	with open(fname, 'w') as outfile:
		json.dump(data, outfile) 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: geojson_tools.py    From mltools with MIT License 5 votes vote down vote up
def filter_by_property(input_file, output_file, property_name, values):
    '''
    Create a file containing only features with specified property value(s) from
        input_file.

    INPUT   input_file (str): File name.
            output_file (str): Output file name.
            property_name (str): Name of the feature property to filter by.
            values (list): Value(s) a feature may have for property_name if it is to be
                included in output_file.
    '''

    filtered_feats = []
    if not output_file.endswith('.geojson'):
        output_file += '.geojson'

    # Load feature list
    with open(input_file) as f:
        feature_collection = geojson.load(f)

    # Filter feats by property_name
    for feat in feature_collection['features']:
        if feat['properties'][property_name] in values:
            filtered_feats.append(feat)

    feature_collection['features'] = filtered_feats

    # Save filtered file
    with open(output_file, 'wb') as f:
        geojson.dump(f) 
Example #9
Source File: test_api.py    From overpass-api-python-wrapper with Apache License 2.0 5 votes vote down vote up
def test_geojson_extended():

    class API(overpass.API):
        def _get_from_overpass(self, query):
            return pickle.load(open(os.path.join(os.path.dirname(__file__), "example.response"), "rb"))

    # The commented code should only be executed once when major changes to the Overpass API and/or to this wrapper are
    # introduced. One than has to manually verify that the date in the  example.response file from the Overpass API
    # matches the data in the example.json file generated by this wrapper.
    #
    # The reason for this approach is the following: It is not safe to make calls to the actual API in this test as the
    # API might momentarily be unavailable and the underlying data can also change at any moment. The commented code is
    # needed to create the example.response and example.json files. The example.response file is subsequently used to
    # fake the _get_from_overpass method during the tests and the example.json file is the reference that we are
    # asserting against.
    #
    # api = overpass.API()
    # osm_geo = api.get("rel(6518385);out body geom;way(10322303);out body geom;node(4927326183);", verbosity='body geom')
    # pickle.dump(api._get_from_overpass("[out:json];rel(6518385);out body geom;way(10322303);out body geom;node(4927326183);out body geom;"),
    #             open(os.path.join(os.path.dirname(__file__), "example.response"), "wb"),
    #             protocol=2)
    # geojson.dump(osm_geo, open(os.path.join(os.path.dirname(__file__), "example.json"), "w"))

    api = API()
    osm_geo = api.get("rel(6518385);out body geom;way(10322303);out body geom;node(4927326183);", verbosity='body geom')
    ref_geo = geojson.load(open(os.path.join(os.path.dirname(__file__), "example.json"), "r"))
    assert osm_geo==ref_geo 
Example #10
Source File: bus_router.py    From bus-router with MIT License 5 votes vote down vote up
def directionscall(google_key, stop, origin, dest, waypoints, fname):
	print "getting dirs..."
	base = 'https://maps.googleapis.com/maps/api/directions/json?'
	params = urllib.urlencode({'origin': origin, 'destination': dest, 'waypoints': waypoints, 'sensor': 'false','key': google_key})
	# print params
	# if waypoints == "":
	with open("log.txt", 'a') as log:
		log.write(base + params + '\n')
	response = urllib.urlopen(base + params)
	data = json.load(response)
	with open(fname, 'w') as outfile:
		json.dump(data, outfile) 
Example #11
Source File: dedupe.py    From robosat with MIT License 4 votes vote down vote up
def main(args):
    with open(args.osm) as fp:
        osm = json.load(fp)

    # Todo: at the moment we load all OSM shapes. It would be more efficient to tile
    #       cover and load only OSM shapes in the tiles covering the predicted shapes.
    osm_shapes = [shapely.geometry.shape(feature["geometry"]) for feature in osm["features"]]
    del osm

    with open(args.predicted) as fp:
        predicted = json.load(fp)

    predicted_shapes = [shapely.geometry.shape(features["geometry"]) for features in predicted["features"]]
    del predicted

    idx = make_index(osm_shapes)
    features = []

    for predicted_shape in tqdm(predicted_shapes, desc="Deduplicating", unit="shapes", ascii=True):
        nearby = [osm_shapes[i] for i in idx.intersection(predicted_shape.bounds, objects=False)]

        keep = False

        if not nearby:
            keep = True
        else:
            intersecting = [shape for shape in nearby if predicted_shape.intersects(shape)]

            if not intersecting:
                keep = True
            else:
                intersecting_shapes = functools.reduce(lambda lhs, rhs: lhs.union(rhs), intersecting)

                if iou(predicted_shape, intersecting_shapes) < args.threshold:
                    keep = True

        if keep:
            feature = geojson.Feature(geometry=shapely.geometry.mapping(predicted_shape))
            features.append(feature)

    collection = geojson.FeatureCollection(features)

    with open(args.out, "w") as fp:
        geojson.dump(collection, fp) 
Example #12
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) 
Example #13
Source File: geojson_tools.py    From mltools with MIT License 4 votes vote down vote up
def write_properties_to(data, property_names, input_file, output_file, filter=None):
    '''
    Writes property data to polygon_file for all
       geometries indicated in the filter, and creates output file.
       The length of data must be equal to the number of geometries in
       the filter. Existing property values are overwritten.

       Args:
           data (list): List of tuples. Each entry is a tuple of dimension equal
                        to property_names.
           property_names (list): Property names.
           input_file (str): Input file name.
           output_file (str): Output file name.
           filter (dict): Filter format is {'property_name':[value1,value2,...]}.
                          What this achieves is to write the first entry of data
                          to the properties of the feature with
                          'property_name'=value1, and so on. This makes sense only
                          if these values are unique. If Filter=None, then
                          data is written to all geometries in the input file.
    '''

    with open(input_file) as f:
        feature_collection = geojson.load(f)

    features = feature_collection['features']

    if filter is None:
        for i, feature in enumerate(features):
            for j, property_value in enumerate(data[i]):
                feature['properties'][property_names[j]] = property_value
    else:
        filter_name = filter.keys()[0]
        filter_values = np.array(filter.values()[0])
        for feature in features:
            compare_value = feature['properties'][filter_name]
            ind = np.where(filter_values == compare_value)[0]
            if len(ind) > 0:
                for j, property_value in enumerate(data[ind][0]):
                    feature['properties'][property_names[j]] = property_value

    feature_collection['features'] = features

    with open(output_file, 'w') as f:
        geojson.dump(feature_collection, f) 
Example #14
Source File: geojson_tools.py    From mltools with MIT License 4 votes vote down vote up
def create_balanced_geojson(input_file, classes, output_file='balanced.geojson',
                            samples_per_class=None):
    '''
    Create a geojson comprised of balanced classes from input_file for training data.
        Randomly selects polygons from all classes.

    INPUT   input_file (str): File name
            classes (list[str]): Classes in input_file to include in the balanced
                output file. Must exactly match the 'class_name' property in the features
                of input_file.
            output_file (str): Name under which to save the balanced output file.
                Defualts to balanced.geojson.
            samples_per_class (int or None): Number of features to select per class in
                input_file. If None will use the smallest class size. Defaults to None.
    '''

    if not output_file.endswith('.geojson'):
        output_file += '.geojson'

    with open(input_file) as f:
        data = geojson.load(f)

    # Sort classes in separate lists
    sorted_classes = {clss : [] for clss in classes}

    for feat in data['features']:
        try:
            sorted_classes[feat['properties']['class_name']].append(feat)
        except (KeyError):
            continue

    # Determine sample size per class
    if not samples_per_class:
        smallest_class = min(sorted_classes, key=lambda clss: len(sorted_classes[clss]))
        samples_per_class = len(sorted_classes[smallest_class])

    # Randomly select features from each class
    try:
        samps = [random.sample(feats, samples_per_class) for feats in sorted_classes.values()]
        final = [feat for sample in samps for feat in sample]
    except (ValueError):
        raise Exception('Insufficient features in at least one class. Set ' \
                            'samples_per_class to None to use maximum amount of '\
                            'features.')

    # Shuffle and save balanced data
    np.random.shuffle(final)
    data['features'] = final

    with open(output_file, 'wb') as f:
        geojson.dump(data, f) 
Example #15
Source File: bus_router.py    From bus-router with MIT License 4 votes vote down vote up
def shapesToGeojson():
	json_data=open('data.txt')
	datadir = os.path.join(os.getcwd(), 'data')
	gtfsdir = os.path.join(datadir, 'gtfs')
	geojsondir = os.path.join(datadir, 'geojson')
	data = json.load(json_data, object_hook=_decode_dict)
	json_data.close()
	with open(gtfsdir + "/shapes.txt", 'rb') as shapesfile:
		shapesreader = csv.DictReader(shapesfile)
		keys = shapesreader.fieldnames

		jsonpoints = []
		features = []
		currentTrip = ''
		for i, point in enumerate(shapesreader):
			if point['shape_pt_sequence'] == '0':
				print 'creating trip'
				currentTrip = point['shape_id']
				if i > 0:
					ls = LineString(jsonpoints)
					feature = Feature(geometry=ls, properties={"shape_id": currentTrip})
					# print feature
					features.append(feature)
					jsonpoints = []
			else:
				pnt = (float(point['shape_pt_lon']), float(point['shape_pt_lat']))
				# print pnt
				jsonpoints.append(pnt)

		# write linestring for last shape
		ls = LineString(jsonpoints)
		feature = Feature(geometry=ls, properties={"shape_id": currentTrip})
		print feature
		features.append(feature)
		jsonpoints = []		
		fc = FeatureCollection(features)
		print fc

		geojsonfile = os.path.join(geojsondir, 'shapes.geojson')

		with open(geojsonfile, 'wb') as tripgeo:
			geojson.dump(fc, tripgeo)