Ejemplo n.º 1
0
 def get(self, route_id):
     if route_id:
         r = OrderedDict([])
         route_properties = get_route_properties(route_id)
         r["route_info"] = route_properties
         route_stop_positions = get_route_stop_positions(route_id)
         geo_stops = [Point((sp["lat"], sp["lon"])) for sp in route_stop_positions]
         r["stop_positions"] = GeometryCollection(geo_stops)
         route_stops = get_route_stops_with_connections(route_id)
         for s in route_stops:
             if s["member_type"] == 0:
                 s["osm_id"] = "node/"
             elif s["member_type"] == 1:
                 s["osm_id"] = "way/"
             else:
                 s["osm_id"] = "relation/"
             s["osm_id"] = s["osm_id"] + str(s["member_osm_id"])
             s.pop("member_type")
             s.pop("member_osm_id")
             s.pop("geojson")
         r["stop_list"] = route_stops
         r["geometry"] = ast.literal_eval(get_route_geojson(route_id))
         r["attribution"] = ATTRIBUTION
         return r
     else:
         return {}
Ejemplo n.º 2
0
def test_bbox_geometry_collection():
    my_point = Point((23.532, -63.12))
    my_line = LineString([(-152.62, 51.21), (5.21, 10.69)])
    geo_collection = GeometryCollection([my_point, my_line])
    bb = bbox(geo_collection)
    assert bb[0] == -152.62
    assert bb[1] == -63.12
    assert bb[2] == 23.532
    assert bb[3] == 51.21
Ejemplo n.º 3
0
def geojson_from_mask(mask,
                      transform,
                      min_aspect_ratio=1.618,
                      min_area=None,
                      width_factor=0.5,
                      thickness=0.001):
    polygons = geometries_from_mask(mask, transform, min_aspect_ratio,
                                    min_area, width_factor, thickness)
    return geojson.dumps(GeometryCollection(polygons))
Ejemplo n.º 4
0
def to_geometry_collection(regions, vertices):
    # create polygons from regions and vertices
    geometry_polygons = []
    for region in regions:
        polygon = vertices[region]
        points = []
        for point in polygon:
            points.append((point[0], point[1]))
        json_polygon = Polygon([points])
        geometry_polygons.append(json_polygon)
    geometry_collection = GeometryCollection(geometry_polygons)
    return geometry_collection
Ejemplo n.º 5
0
def graph_to_geojson(g):
    geoms = []
    for node_id, node in g.node.iteritems():
        geoms.append(Point([node['data'].lon, node['data'].lat]))

    for from_id, to_id in g.edges_iter():
        from_ = g.node[from_id]['data']
        to_ = g.node[to_id]['data']
        geoms.append(LineString([
            (from_.lon, from_.lat),
            (to_.lon, to_.lat),
            ]))

    return GeometryCollection(geoms)
Ejemplo n.º 6
0
    def geometry_collection(self, count_limit=10):
        """
        Returns a specific number of random geojson geometries as a geometry collection
        """
        features = [
            self.point(),
            self.multipoint(count_limit=10),
            self.linestring(node_limit=100),
            self.multilinestring(count_limit=10, node_limit=100),
            self.multipolygon()
        ]

        return GeometryCollection(
            [choice(features) for i in range(count_limit)])
Ejemplo n.º 7
0
def createBrisbaneArea(filename=''):
    try:
        if not filename or len(filename) == 0:
            filename = os.getenv('GEOJSON_FILE')
        with open(filename) as fp:
            geoObj = geojson.load(fp)
            if not geoObj.is_valid:
                raise SpaceKnowError('Invalid GeoJson file!', 400)
            brisbaneArea = GeometryCollection([geoObj['geometry']])
            if not brisbaneArea.is_valid:
                raise SpaceKnowError("Invalid GeoJson Object", 400)
            return brisbaneArea
    except FileNotFoundError:
        logger.error("Error: file %s not found" % os.getenv('GEOJSON_FILE'))
        exit()
Ejemplo n.º 8
0
def df_to_geojson(df, export_path=None, lat_row='Latitude', lng_row='Longitude'):
    """ 
   
    Konvertiert das Dataframe der GPS Sensoraufnahme (GPS.csv) in GeoJSON (ohne Index-Berechnung). 
    """
    points = []
    for i in range(0, len(df)):
        x = df.iloc[i]
        p = Point(str_to_float(x[lng_row]), str_to_float(x[lat_row]))
        
        points.append(p)
    
    _geojson = GeometryCollection(points)
    
    if export_path:
        f = open (export_path, 'w')
        f.write(json.dumps(_geojson))
    return _geojson
Ejemplo n.º 9
0
def main(input_file):
    with open(input_file) as f:
        graph = pickle.load(f)

    node_map = {int(node_id): i for i, node_id in enumerate(graph.nodes())}

    outcomes = []
    for fn, name in [
        ('data/sfnodesdtINTOXICATIONCRIME.csv', 'intoxication'),
        ('data/sfnodesdtPROPERTYCRIME.csv', 'property'),
        ('data/sfnodesdtVIOLENTCRIME.csv', 'violent'),
    ]:
        df = pd.read_csv(fn)
        df['crime_type'] = name
        outcomes.append(df)

    df = pd.concat(outcomes)
    df['id'] = df['id'].apply(node_map.get)

    df = df[df['id'].notnull()]

    for (tod, dow), time_df in df.groupby(['daytime', 'superday']):

        points = []
        for node_id, node_df in time_df.groupby('id'):

            # so so sorry future sean
            values = node_df[['id', 'crime_type', 'preds'
                              ]].set_index('crime_type').to_dict()['preds']

            points.append(
                Point([node_df['Y'].values[0], node_df['X'].values[0]],
                      node_id=node_id,
                      **values))

        geo = GeometryCollection(points)
        outfile = 'www/json/sf_crime_{}_{}.json'.format(
            tod.lower().replace('-', '_'), dow.lower())
        with open(outfile, 'w') as f:
            dump(geo, f)
Ejemplo n.º 10
0
 def _as_geojson_instance(cls, geojson_dict):
     try:
         geojson = GeoJSON.to_instance(geojson_dict, strict=True)
     except (TypeError, KeyError, UnicodeEncodeError) as ex:
         raise ValueError(
             "geometry not recognized as valid GeoJSON ({}): {}".format(
                 str(ex), geojson_dict))
     # Shapely cannot handle GeoJSON Features or FeatureCollections
     if isinstance(geojson, Feature):
         geojson = geojson.geometry
     elif isinstance(geojson, FeatureCollection):
         features = []
         for feature in geojson.features:
             try:
                 features.append(
                     GeoJSON.to_instance(feature, strict=True).geometry)
             except (TypeError, KeyError, UnicodeEncodeError) as ex:
                 raise ValueError(
                     "feature in FeatureCollection not recognized as valid ({}): {}"
                     .format(str(ex), feature))
         geojson = GeometryCollection(features)
     return geojson
Ejemplo n.º 11
0
def processPolylines():
    encoder = gpolyencode.GPolyEncoder()
    json_data = open('data.txt')
    datadir = os.path.join(os.getcwd(), 'data')
    gtfsdir = os.path.join(datadir, 'gtfs')
    geojsondir = os.path.join(datadir, 'geojson')
    polydir = os.path.join(datadir, 'polylines')
    data = json.load(json_data, object_hook=_decode_dict)
    # pprint(data)
    json_data.close()
    with open(gtfsdir + "/shapes.txt", 'wb') as shapesfile:
        shapeswriter = csv.writer(shapesfile)
        shapeswriter.writerow([
            "shape_id", "shape_pt_sequence", "shape_dist_traveled",
            "shape_pt_lon", "shape_pt_lat"
        ])
        for trip, stops in data.items():
            print trip

            legpoints = []
            jsonpoints = []

            for i in range(20):
                filepath = os.path.join(polydir, trip + "_" + str(i) + ".json")
                if (os.path.exists(filepath)):
                    gmaps = open(filepath)

                    linedata = json.load(gmaps)
                    print trip + "_" + str(i)
                    if args.dir == 'goog':
                        if linedata['status'] != "OK":
                            continue
                        print linedata['routes'][0]['overview_polyline'][
                            'points']
                        points = decode(linedata['routes'][0]
                                        ['overview_polyline']['points'])
                        # print points
                        for point in points:
                            dictpoint = {'x': point[0], 'y': point[1]}

                            legpoints.append(dictpoint)
                        gmaps.close()
                    elif args.dir == 'osrm':
                        if linedata['status'] != 0:
                            continue
                        print linedata['route_geometry']
                        points = decode(linedata['route_geometry'])
                        # print points
                        for point in points:
                            dictpoint = {
                                'x': point[0] / 10,
                                'y': point[1] / 10
                            }

                            legpoints.append(dictpoint)

                        gmaps.close()

            # print legpoints

            # print ls.geojson
            if not legpoints:
                continue
            else:
                simplified = simplify(legpoints, .0002, True)
                # print "new:" + str(simplified)
                count = 0
                for point in simplified:
                    jsonpoints.append((point['x'], point['y']))
                    shppoint = [point['x'], point['y']]
                    shppoint.insert(0, trip)
                    shppoint.insert(1, count)
                    shppoint.insert(2, "")
                    shapeswriter.writerow(shppoint)
                    count += 1
                ls = LineString(jsonpoints)
                gc = GeometryCollection([ls])

                gtfsfile = os.path.join(geojsondir, trip + '.geojson')

                with open(gtfsfile, 'wb') as tripgeo:
                    geojson.dump(gc, tripgeo)
Ejemplo n.º 12
0
for section in section_of_lines:

    sol = SectionOfLine(start={'id': section.find('SOLOPStart').get('Value')},
                        end={'id': section.find('SOLOPEnd').get('Value')})
    start_op_point = tree.find(
        './/OperationalPoint/UniqueOPID[@Value="%s"]/...' % sol.start['id'])
    end_op_point = tree.find(
        './/OperationalPoint/UniqueOPID[@Value="%s"]/...' % sol.end['id'])
    if start_op_point == None or end_op_point == None:
        print('no start or end op point for section of line: %s' % sol)
        continue

    start_op_point_coords = start_op_point.find('OPGeographicLocation')
    end_op_point_coords = start_op_point.find('OPGeographicLocation')

    sol.start['coords'] = (float(
        start_op_point_coords.get('Longitude').replace(',', '.')),
                           float(
                               start_op_point_coords.get('Latitude').replace(
                                   ',', '.')))
    sol.end['coords'] = (float(
        end_op_point_coords.get('Longitude').replace(',', '.')),
                         float(
                             end_op_point_coords.get('Latitude').replace(
                                 ',', '.')))
    line_strings.append(LineString([sol.start['coords'], sol.end['coords']]))

geometry_collection = GeometryCollection(line_strings)
print(geojson.dumps(geometry_collection))
Ejemplo n.º 13
0
def run(key):
    print("starting create_geojson.run with key " + key)

    from django.db import connection
    connection.close()

    features = []
    for fp in FeaturePlace.objects.filter(
            feature__order__token=key,
            correct=True).order_by("-place__admin_level"):

        properties = {}

        feature = fp.feature

        if feature.end:
            properties['end_time'] = feature.end.strftime('%y-%m-%d')

        if feature.start:
            properties['start_time'] = feature.start.strftime('%y-%m-%d')

        properties['confidence'] = float(fp.confidence)
        place = fp.place
        properties['admin_level'] = place.admin_level
        properties['admin1_code'] = place.admin1_code
        properties['country_code'] = place.country_code
        try:
            importance = place.wikipedia.importance
        except:
            importance = 0
        properties['importance'] = importance
        properties['name'] = place.name
        properties['geonames_id'] = place.geonames_id
        properties['pcode'] = place.pcode
        properties['timezone'] = place.timezone
        point = Point((place.point.x, place.point.y))
        geometries = [point]
        if place.mpoly:
            coords = place.mpoly.coords
            length_of_coords = len(coords)
            if length_of_coords == 1:
                geometries.append(Polygon(coords[0]))
            elif length_of_coords > 1:
                geometries.append(MultiPolygon(coords))
        gc = GeometryCollection(geometries)
        features.append(gFeature(geometry=gc, properties=properties))
    featureCollection = FeatureCollection(features)

    directory = join(MAPS_DIRECTORY, key)
    if not isdir(directory):
        mkdir(directory)

    serialized = dumps(featureCollection, sort_keys=True)
    with open(join(directory, key + ".geojson"), "w") as f:
        f.write(serialized)

    print("I finished running create_geojson.  You can view the map here:")
    url = PUBLIC_BASE_URL + "/api/orders/" + key + "/maps/geojson"
    quoted = quote(url)
    print("http://geojson.io/#data=data:text/x-url," + quoted)

    print(PUBLIC_BASE_URL + "/api/orders/" + key + "/maps/geojson")
Ejemplo n.º 14
0
Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
###############################################################################
Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)],
         [(-5.21, 23.51), (15.21, -10.81), (-20.51, 1.51), (-5.21, 23.51)]])
###############################################################################
from geojson import MultiPolygon
MultiPolygon([([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234),
                (3.78, 9.28)], ),
              ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91),
                (23.18, -34.29)], )])
###############################################################################
from geojson import GeometryCollection, Point, LineString
from pprint import pprint
my_point = Point((23.532, -63.12))
my_line = LineString([(-152.62, 51.21), (5.21, 10.69)])
pprint(GeometryCollection([my_point, my_line]))
###############################################################################
from geojson import Feature, Point
my_point = Point((-3.68, 40.41))
Feature(geometry=my_point)  # doctest: +ELLIPSIS
###############################################################################
Feature(geometry=my_point, properties={"country":
                                       "Spain"})  # doctest: +ELLIPSIS
###############################################################################
Feature(geometry=my_point, id=27)  # doctest: +ELLIPSIS
###############################################################################
from geojson import FeatureCollection
my_feature = Feature(geometry=Point((1.6432, -19.123)))
my_other_feature = Feature(geometry=Point((-80.234, -22.532)))
pprint(FeatureCollection([my_feature, my_other_feature]))
Ejemplo n.º 15
0
def write_points_to_geojson(points, file_name, sample=1):
    geo_collection = GeometryCollection(
        [Point((coord[0], coord[1])) for coord in points[::1]])

    with open(file_name, 'w') as out_file:
        out_file.write(json.dumps(geo_collection))