Example #1
0
    def get_nearest_intersection_from_point(lat, lon, **kwargs):
        if not ((type(lat) == int or type(lat) == float) and (type(lat) == int or type(lat) == float)):
            raise ValueError("Both lat and lon must be numeric")

        c = kwargs['cursor']
        intersection_lookup_sql = """
            WITH road_dis AS (
                SELECT intersection_point AS road_location, ST_Distance(ST_Transform(ST_GeomFromText('POINT(-91 30)', 4326), 4269), geom, true) AS road_distance
                FROM roads_intersection ri
                ORDER BY ST_Distance(ST_Transform(ST_GeomFromText('POINT({0} {1})', 4326), 4269), geom, true) ASC
                LIMIT 1
            ),
            place_dis AS(
                SELECT gid AS place_id, name AS place_name, location AS place_location, ST_Distance(ST_Transform(ST_GeomFromText('POINT(-91 30)', 4326), 4269), geom, true) AS place_distance
                FROM places_intersection pi
                ORDER BY ST_Distance(ST_Transform(ST_GeomFromText('POINT({0} {1})', 4326), 4269), geom, true) ASC
                LIMIT 1
            )

            SELECT r.*, p.*
            FROM road_dis r, place_dis p
        """.format(str(lon), str(lat))

        in_town_sql = """
            SELECT gid, name
            FROM gis.places p
            WHERE ST_Within(ST_Transform(ST_GeomFromText('POINT({0} {1})', 4326), 4269), p.geom)
        """.format(str(lon), str(lat))

        c.execute(intersection_lookup_sql)
        road_location, road_distance, place_id, place_name, place_location, place_distance = c.fetchone()

        c.execute(in_town_sql)
        row = c.fetchone()
        in_town_id, in_town_name = row if row is not None else (None, None)

        return {
            "node_id": get_node_name_from_location(shapely.wkt.road_location) if road_distance < place_distance else place_id,
            "nearest_town": place_name,
            "in_town_id": in_town_id,
            "in_town_name": in_town_name
        }