Ejemplo n.º 1
0
def create_stop_location_detail(title, latitude, longitude, index,
                                route_index):
    point = Point([longitude, latitude])
    properties = {
        "title": title,
        'icon': "campsite",
        'marker-color': '#6B1A74',
        'marker-symbol': index,
        'route_index': route_index
    }
    feature = Feature(geometry=point, properties=properties)
    return feature
def get_points(camp_id): #update name to id after testing
    """will return a set of coordinates"""

    campsite = session.query(Campsite).filter_by(campsite_id=camp_id).first()
    lat = campsite.lat
    lon = campsite.lon
    if lon > 0:
        lon = lon * -1
    point = Point((lon, lat))
    session.close()

    return point
Ejemplo n.º 3
0
def addpts(pt1, pt2, wt):
    lat1 = pt1['geometry']['coordinates'][1]
    lat2 = pt2['geometry']['coordinates'][1]

    lon1 = pt1['geometry']['coordinates'][0]
    lon2 = pt2['geometry']['coordinates'][0]

    newlat = (lat1 * (1 - wt)) + lat2 * wt
    newlon = (lon1 * (1 - wt)) + lon2 * wt

    newpt = Feature(geometry=Point((newlon, newlat)))
    return newpt
Ejemplo n.º 4
0
def create_yost():

    proto = places_data_manager.min_place_dict

    place = proto.copy()
    place['name'] = 'Yost Hall'
    place['type'] = 'CampusBuilding'
    place['geo_coordinates'] = Point((-81.608950, 41.503553))
    place['senti_score'] = -3.55
    place['rating_average'] = 3.9
    place['rating_count'] = 21
    return place
Ejemplo n.º 5
0
def write_geojson(file, output_file):
    features = []
    for i, row in file.iterrows():
        if i % 50_000 == 0:
            logger.info('Processed %s / %s adresses', i, len(file))
        point = Point((row['EPSG:4326_lon'], row['EPSG:4326_lat']))
        properties = {
            key: val
            for key, val in row.to_dict().items()
            if not pd.isnull(val) and 'EPSG:' not in key
        }
        features.append(Feature(geometry=point, properties=properties))
Ejemplo n.º 6
0
def create_geojson_feature(point, properties={}, feature_id=None):
    """
    point is a (lon, lat) tuple,
    properties is a dictionary (e.g. {'country': 'Spain})
    """

    gj_point = Point(point)
    gj_feature = Feature(geometry=gj_point,
                         properties=properties,
                         id=feature_id)

    return gj_feature
Ejemplo n.º 7
0
def event_to_geojson(x,y,userID,eventID,firstName,lastName,eventName,startTime,endTime,description,attendance,attending):
    return Feature(geometry=Point((x,y)),\
    properties={"userID":userID,\
    "eventID":eventID,\
    "firstName":firstName,\
    "lastName":lastName,\
    "eventName":eventName,\
    "startTime":startTime,\
    "endTime":endTime,\
    "description":description,\
    "attendance":attendance,\
    "attending":attending})
Ejemplo n.º 8
0
def create_thwing():

    proto = places_data_manager.min_place_dict

    place = proto.copy()
    place['name'] = 'Thwing Student Center'
    place['type'] = 'CampusBuilding'
    place['geo_coordinates'] = Point((-81.608199, 41.507386))
    place['senti_score'] = 6
    place['rating_average'] = 4
    place['rating_count'] = 14
    return place
Ejemplo n.º 9
0
def test_boolean_point_in_polygon():
    point = Feature(geometry=Point((-77, 44)))
    polygon = Feature(
        geometry=MultiPolygon(
            [
                ([(-81, 41), (-81, 47), (-72, 47), (-72, 41), (-81, 41)],),
                ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],),
            ]
        )
    )
    bpp = boolean_point_in_polygon(point, polygon)
    assert bpp == True
Ejemplo n.º 10
0
def get_all_visits_user_geojson(user_id):
    visits = user_traces_db.load_user_all_visits_per_place(user_id)
    features = []
    for v in visits:
        features.append(
            Feature(geometry=Point((v['lon'], v['lat'])),
                    properties={
                        "dur": v['dur'],
                        "nb_visits": v['nb_visits']
                    }))

    return FeatureCollection(features)
Ejemplo n.º 11
0
def get_pm10_points_as_geojson(source):
    pm10_data = get_pm10_data(source)

    features = []
    for index, measurement in enumerate(pm10_data['measurements']):
        polygon = Point(
            (pm10_data['longitudes'][index], pm10_data['latitudes'][index]))
        features.append(
            Feature(geometry=polygon, properties={"value": measurement}))

    feature_collection = FeatureCollection(features)
    return feature_collection
Ejemplo n.º 12
0
    def create(self, validated_data):

        plan_file_json = validated_data['plan_file_json']
        plan_file = self.parse_and_validate_plan_file(
            plan_file_json=plan_file_json)
        all_geo_json_features = []
        for mission_item in plan_file.Mission.Items:
            if isinstance(mission_item, SimpleMissionItem):
                if mission_item.Params[5] and mission_item.Params[4]:
                    p = Point([mission_item.Params[5], mission_item.Params[4]])
                    all_geo_json_features.append(Feature(geometry=p))

            elif isinstance(mission_item, ComplexMissionItem):

                if mission_item.Polygon != 0:
                    all_polygon_points = []
                    for polygon_coordinates in mission_item.Polygon:
                        p = Point(
                            [polygon_coordinates[1], polygon_coordinates[0]])
                        all_polygon_points.append(p)

                    polygon = Polygon(all_polygon_points)

                    all_geo_json_features.append(Feature(geometry=polygon))

                if mission_item.Polyline != 0:
                    all_polyline_points = []
                    for polyline_coordinates in mission_item.Polyline:
                        p = Point(
                            [polyline_coordinates[1], polyline_coordinates[0]])

                        all_polyline_points.append(p)
                    polyline = LineString(all_polyline_points)
                    all_geo_json_features.append(Feature(geometry=polyline))

        feature_collection = FeatureCollection(all_geo_json_features)
        validated_data['geo_json'] = json.loads(
            geojson.dumps(feature_collection))

        return super(FlightPlanSerializer, self).create(validated_data)
Ejemplo n.º 13
0
    def _getStreets(regions: FeatureCollection) -> MultiLineString:
        """Collect a set of Ways (from OSM) and convert them to a MultiLineString"""

        overpassQueryUrl = OSMMiner._createCollectStreetsQuery(regions)

        OSMMiner._lock.acquire()
        #write_to_log("Rate limit %d, current queries: %d \n" % (OSMMiner._rateLimit, OSMMiner._currentQueries))
        write_to_log(f'OSMMiner._OSMServerURL: {OSMMiner._OSMServerURL}')
        #write_to_log(f'overpassQueryUrl: {overpassQueryUrl}')
        
        while OSMMiner._currentQueries >= OSMMiner._rateLimit:
            time.sleep(1)
        OSMMiner._waitForAvailableSlots()
        OSMMiner._currentQueries += 1
        ##DEBUG
        #print("added query: %d\n" % OSMMiner._currentQueries)
        OSMMiner._lock.release()
        jsonString = requests.get(overpassQueryUrl).content
        OSMMiner._currentQueries -= 1
        ##DEBUG
        #print("removed query: %d\n" % OSMMiner._currentQueries)
        try:
            #TODO: Treat cases in which the OSM server fails
            osmResult = OSMResult.fromJsonString(jsonString)
        except:
            write_to_log("Error while parsing overpass message. Message sample: %s" % jsonString[:100])
            raise AttributeError("Invalid jsonString")
        streetSegments = {}
        
        # Data needs to be sorted before being grouped, otherwise
        # the same group may appear multiple times
        data = sorted(osmResult.Ways.values(), key=lambda x: x.tags.get('name'))
        g = groupby(data, lambda x: x.tags.get('name'))
        for streetName, group in g:
            nodesList = [x.nodes for x in group]
            OSMMiner._mergeWays(nodesList)
            if streetName in streetSegments:
                streetSegments[streetName] = streetSegments[streetName] + nodesList
            else:
                streetSegments[streetName] = nodesList
        featuresList = []
        for streetName in streetSegments:
            featuresList.append(
                Feature(id=streetName, 
                    properties={'name':streetName}, 
                    geometry=MultiLineString([LineString([
                    Point([osmResult.Nodes[n].lon, 
                    osmResult.Nodes[n].lat]) for n in s]) 
                    for s in streetSegments[streetName]]))
            )
           
        return FeatureCollection(featuresList, crs=OSMMiner._crs)
Ejemplo n.º 14
0
Archivo: gjson.py Proyecto: QilinGu/geo
    def writePointsFeatureCollection(self,latlons,colors,varname):
        featureCollection = {'features':[]}
        print latlons.shape,colors.shape
        for latlon,color in zip(latlons,colors):
            hexcolor = self.rgb2hex(color)
            st = {"fillcolor": hexcolor, "radius":40}
            #st = {"fillOpacity":0.3, "fillcolor": hexcolor, "color":hexcolor,"radius":40, "stroke":False}
            pr = {"style":st}
            ft = Feature(geometry=Point(latlon.tolist()), properties=pr)
            featureCollection['features'].append(ft)

        print>>self.outfile, "var %s = "%(varname)
        geojson.dump(featureCollection,self.outfile)
Ejemplo n.º 15
0
def to_geojson(json_string, route):
    stops = json.loads(json_string)
    features = []
    for stop in stops:
        point = Point((stop["lng"], stop["lat"]))
        feature = Feature(geometry=point,
                          properties={
                              "id": stop["stopid"],
                              "route": route,
                              "name": stop["stopname"]
                          })
        features.append(feature)
    return dumps(FeatureCollection(features))
Ejemplo n.º 16
0
    def transform(self, values):
        for value in values:
            polygon = loads(value['geom'])
            coordinates = polylabel(polygon['coordinates'][0])
            value['geom'] = Point(coordinates,
                                  crs={
                                      'type': 'name',
                                      'properties': {
                                          'name': 'EPSG:3857'
                                      }
                                  })

        return values
Ejemplo n.º 17
0
    def transform(self, values):
        features = []
        for value in values:
            type = value['other_tags'].get('seamark:type')
            features.append(
                Feature(geometry=Point(loads(value['geom'])),
                        properties={
                            'osm_ref': value['osm_id'] + 'n',
                            'type':
                            'minor' if type == 'light_minor' else 'major'
                        }))

        return features
Ejemplo n.º 18
0
 def get(self, lng, lat):
     try:
         lnglat = map(float, (lng, lat))
     except Exception:
         raise tornado.web.HTTPError(400)
     sampler = TileSampler()
     pixel = CoordSystem.lnglat_to_pixel(lnglat)
     print 'Getting elevation at lng,lat:%s,%s %s,%s:' % (lng, lat, pixel[0], pixel[1])
     value = yield sampler.sample_pixel(pixel)
     lnglat = CoordSystem.pixel_to_lnglat(pixel)
     self.write_geojson(Feature(geometry=Point(lnglat), properties={
         "elevation":float(value)
     }))
def tweetToFeature(tweet):
    """
    Convert a tweet to a GeoJSON Feature
    """
    point = Point(tweet['coordinates']['coordinates'])
    properties = {
        'text': tweet['text'],
        'sentiment': tweet['polarity'],
        'tokens': tweet['tokens']
    }
    feature = Feature(geometry=point, id=tweet['id'], properties=properties)

    return feature
Ejemplo n.º 20
0
def vaccine_to_geojson(data):
    geo = []
    for k, v in data.items():
        geo.append(
            Feature(geometry=Point(
                [float(str(v['longitude'])),
                 float(str(v['latitude']))]),
                    properties={
                        'name': v['name'],
                        'address': v['address']
                    }))
    feature_collection = FeatureCollection(geo)
    return feature_collection
Ejemplo n.º 21
0
def locations():
    lat1 = float(request.args.get('lat1', -90))
    long1 = float(request.args.get('long1', -180))
    lat2 = float(request.args.get('lat2', 90))
    long2 = float(request.args.get('long2', 180))
    features = FeatureCollection(
        [
            Feature(geometry=Point((long, lat)), properties={"count": count})
            for lat, long, count in pd.read_csv("data/unique.csv").values
            if lat1 <= lat <= lat2 and long1 <= long <= long2
        ]
    )
    return jsonify(features)
Ejemplo n.º 22
0
def square(bbox: list):
    """
    Takes a bounding box and calculates the minimum square bounding box that would contain
    the input.

    :param bbox: Bounding box extent in west, south, east, north order
    :return: A square surrounding bbox

    Example:

    >>> from turfpy.measurement import square
    >>> bbox = [-20, -20, -15, 0]
    >>> square(bbox)
    """
    west = bbox[0]
    south = bbox[1]
    east = bbox[2]
    north = bbox[3]

    horizontal_distance = distance(Feature(geometry=Point(bbox[0:2])),
                                   Feature(geometry=Point((east, south))))
    vertical_distance = distance(Feature(geometry=Point(bbox[0:2])),
                                 Feature(geometry=Point((west, north))))
    if horizontal_distance >= vertical_distance:
        vertical_midpoint = (south + north) / 2
        return [
            west,
            vertical_midpoint - ((east - west) / 2),
            east,
            vertical_midpoint + ((east - west) / 2),
        ]
    else:
        horizontal_midpoint = (west + east) / 2
        return [
            horizontal_midpoint - ((north - south) / 2),
            south,
            horizontal_midpoint + ((north - south) / 2),
            north,
        ]
    async def test_search_partner_by_coordinate_be_none_when_no_partner_found(
            self, backend):
        partner = partner_adega_ze_ambev()
        coordinate = [0, 0]

        await backend.save(partner)

        point = Point(coordinate)

        found_partner = await backend.search_nearest_by_coordinate(
            coordinate=point)

        assert found_partner is None
Ejemplo n.º 24
0
def to_geojson_feature(dx: DictAny, properties: Optional[DictAny]=None) -> Feature:
    # More of this raw data from google should be pushed down
    # this ix is perhaps an issue given that the data source isn't
    # persisting UUIDs across updates.
    g = dx["geometry"]["location"]
    coords = g["lng"], g["lat"]
    pt = Point(coords)

    keys = ("formatted_address", "place_id", "plus_code")
    if properties is not None:
        for key in keys:
            properties[key] = dx.get(key)
    return Feature(geometry=pt, properties=properties)
Ejemplo n.º 25
0
def destination(origin: Feature,
                distance,
                bearing,
                options: dict = {}) -> Feature:
    """
    Takes a Point and calculates the location of a destination point given a distance in
    degrees, radians, miles, or kilometers and bearing in degrees.

    :param origin: Start point.
    :param distance: distance upto which the destination is from origin.
    :param bearing: Direction in which is the destination is from origin.
    :param options: Option like units of distance and properties to be passed to
        destination point feature, value
        for units are 'mi', 'km', 'deg' and 'rad'.
    :return: Feature: destination point in at the given distance and given direction.

    Example:

    >>> from turfpy.measurement import destination
    >>> from geojson import Point, Feature
    >>> origin = Feature(geometry=Point([-75.343, 39.984]))
    >>> distance = 50
    >>> bearing = 90
    >>> options = {'units': 'mi'}
    >>> destination(origin,distance,bearing,options)
    """
    coordinates1 = origin["geometry"]["coordinates"]
    longitude1 = radians(float(coordinates1[0]))
    latitude1 = radians(float(coordinates1[1]))
    bearingRad = radians(float(bearing))
    if "units" in options:
        radian = length_to_radians(distance, options["units"])
    else:
        radian = length_to_radians(distance)

    latitude2 = asin((sin(latitude1) * cos(radian)) +
                     (cos(latitude1) * sin(radian) * cos(bearingRad)))
    longitude2 = longitude1 + atan2(
        sin(bearingRad) * sin(radian) * cos(latitude1),
        cos(radian) - sin(latitude1) * sin(latitude2),
    )

    lng = degrees(longitude2)
    lat = degrees(latitude2)

    point = Point((lng, lat))

    return Feature(
        geometry=point,
        properties=options["properties"] if "properties" in options else {},
    )
Ejemplo n.º 26
0
def query_parks():
    """Return results from users' query based on search profile."""

    user_id = session.get('user')

    origin_input = request.args.get('origin')
    time = request.args.get('time')
    routing = request.args.get('routing')
    playgrounds = request.args.get('playgrounds')

    origin = geocode_location(origin_input)
    # session['waypoints'].append(origin)

    parks = Park.query.filter(~Park.name.contains('Playground')). \
                       join(Image).filter(Image.image_url != None)

    # Create a dictionary containing parks within the bounding radius heuristic
    close_parks = find_close_parks(origin, time, routing, parks)

    # Create a list of GeoJSON objects for close parks
    geojson_destinations = [
        park.create_geojson_object(user_id) for park in close_parks.values()
    ]

    # Convert origin coordinates to GeoJSON object
    geojson_origin = Feature(geometry=Point((origin.longitude,
                                             origin.latitude)))

    routing_params = [geojson_origin] + geojson_destinations
    # TODO: will add_rounting_time() take these params as two separate lists?

    # Create distance matrix (routing time in seconds)
    routing_times = get_routing_times(routing_params, routing)

    # Create markers for the user's query results by adding routing times to each
    # park's properties
    all_markers = add_routing_time(geojson_destinations, routing_times)

    markers = json.dumps(FeatureCollection(all_markers))

    session['origin'] = [origin.longitude, origin.latitude]
    session['routing'] = routing

    return render_template('query.html',
                           origin=origin,
                           time=time,
                           routing=routing,
                           geojson_origin=geojson_origin,
                           geojson_destinations=geojson_destinations,
                           all_markers=all_markers,
                           markers=markers)
Ejemplo n.º 27
0
    def save(self, calculator):

        allPointsFeature = []
        allPolygonsFeature = []

        # polygon
        for line_index, line in enumerate(calculator.points):
            for point_index, point in enumerate(line):

                name = "{}".format(point_index)
                lineName = "{}".format(line_index)

                polygon = []
                rect = calculator.calculate_footprint_from(point)
                polygon.append([(rect[0][0], rect[0][1]),
                                (rect[1][0], rect[1][1]),
                                (rect[2][0], rect[2][1]),
                                (rect[3][0], rect[3][1])])

                feature = Feature(
                    geometry=Polygon(polygon),
                    properties={"name": "{}-{}".format(lineName, point_index)})
                allPolygonsFeature.append(feature)

        # points
        for line_index, line in enumerate(calculator.points):
            for point_index, point in enumerate(line):

                name = "{}".format(point_index)
                lineName = "{}".format(line_index)
                #allPoints.append((line_index, point_index, point[0], point[1]))
                #allPoints.append(Point(point[0], point[1]))
                feature = Feature(geometry=Point((point[0], point[1])),
                                  properties={
                                      "name":
                                      "{}-{}".format(lineName, point_index),
                                      "Z": calculator.flight_height()
                                  })
                allPointsFeature.append(feature)

        allFeatureCollection = FeatureCollection(
            [*allPointsFeature, *allPolygonsFeature])

        self._geojson = dumps(allFeatureCollection)
        if self.filename != '':
            try:
                with open(self.filename, 'w') as file:
                    file.write(self._geojson)
            except:
                return False
        return True
Ejemplo n.º 28
0
def test_nearest_point_on_line():
    pt = Point([2.5, 1.75])
    ls = Feature(geometry=LineString([(1, 2), (2, 2), (3, 2)]))
    opts = {"key1": "value1", "key2": "value2"}

    npl = nearest_point_on_line(ls, pt, options={"properties": opts.copy()})

    assert npl.geometry["type"] == "Point"
    assert npl.properties["index"] == 1
    assert 27.798 == approx(npl.properties["dist"], abs=1e-3)
    assert 166.682 == approx(npl.properties["location"], abs=1e-3)
    assert npl.geometry.coordinates == approx([2.5, 2], abs=1e-3)
    for key in opts.keys():
        assert npl.properties[key] == opts[key]
Ejemplo n.º 29
0
 def to_geojson(df, columns=None, latlon=['lat', 'lon']):
     """GEOJSON output formatting.
     """
     try:
         assert columns is None or isinstance(columns, string_types)     or \
             (isinstance(columns, Sequence) and all([isinstance(c,string_types) for c in columns]))
     except:
         raise IOError("Wrong format for input columns")
     try:
         lat, lon = latlon
         assert isinstance(lat, string_types) and isinstance(
             lon, string_types)
     except:
         raise TypeError("Wrong format for input lat/lon columns")
     if isinstance(columns, string_types):
         columns == [
             columns,
         ]
     if columns in (None, []):
         columns = list(set(df.columns))
     columns = list(
         set(columns).intersection(set(df.columns)).difference(
             set([lat, lon])))
     # df.reindex(columns = columns) # not necessary
     if _is_geojson_imported is True:
         features = df.apply(lambda row: Feature(geometry=Point(
             (float(row[lon]), float(row[lat])))),
                             axis=1).tolist()
         properties = df[columns].to_dict(
             'records')  # columns used as properties
         # properties = df.drop([lat, lon], axis=1).to_dict('records')
         geom = FeatureCollection(features=features, properties=properties)
     else:
         geom = {'type': 'FeatureCollection', 'features': []}
         for _, row in df.iterrows():
             feature = {
                 'type': 'Feature',
                 'properties': {},
                 'geometry': {
                     'type': 'Point',
                     'coordinates': []
                 }
             }
             feature['geometry']['coordinates'] = [
                 float(row[lon]), float(row[lat])
             ]
             for col in columns:
                 feature['properties'][col] = row[col]
             geom['features'].append(feature)
     return geom
Ejemplo n.º 30
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)