Example #1
0
 def getBoundingLatLngRectFromQueryRadiusInput(
         self, QueryRadiusRequest: 'QueryRadiusRequest'):
     centerPoint = QueryRadiusRequest.getCenterPoint()
     radiusInMeter = QueryRadiusRequest.getRadiusInMeter()
     centerLatLng = S2LatLng.from_degrees(centerPoint.getLatitude(),
                                          centerPoint.getLongitude())
     latReferenceUnit = -1.0 if centerPoint.getLatitude() > 0.0 else 1.0
     latReferenceLatLng = S2LatLng.from_degrees(
         centerPoint.getLatitude() + latReferenceUnit,
         centerPoint.getLongitude())
     lngReferenceUnit = -1.0 if centerPoint.getLongitude() > 0.0 else 1.0
     lngReferenceLatLng = S2LatLng.from_degrees(
         centerPoint.getLatitude(),
         centerPoint.getLongitude() + lngReferenceUnit)
     latForRadius = radiusInMeter / \
         (centerLatLng.get_distance(latReferenceLatLng).radians * EARTH_RADIUS_METERS)
     lngForRadius = radiusInMeter / \
         (centerLatLng.get_distance(lngReferenceLatLng).radians * EARTH_RADIUS_METERS)
     minLatLng = S2LatLng.from_degrees(
         centerPoint.getLatitude() - latForRadius,
         centerPoint.getLongitude() - lngForRadius)
     maxLatLng = S2LatLng.from_degrees(
         centerPoint.getLatitude() + latForRadius,
         centerPoint.getLongitude() + lngForRadius)
     return S2LatLngRect(minLatLng, maxLatLng)
Example #2
0
File: geo.py Project: interuss/dss
def flatten(reference: s2sphere.LatLng,
            point: s2sphere.LatLng) -> Tuple[float, float]:
    """Locally flatten a lat-lng point to (dx, dy) in meters from reference."""
    return ((point.lng().degrees - reference.lng().degrees) *
            EARTH_CIRCUMFERENCE_KM * math.cos(reference.lat().radians) * 1000 /
            360, (point.lat().degrees - reference.lat().degrees) *
            EARTH_CIRCUMFERENCE_KM * 1000 / 360)
Example #3
0
 def queryRadius(self, QueryRadiusInput: 'QueryRadiusRequest'):
     latLngRect = S2Util().getBoundingLatLngRectFromQueryRadiusInput(
         QueryRadiusInput)
     covering = Covering(
         self.config.S2RegionCoverer().get_covering(latLngRect))
     results = self.dispatchQueries(covering, QueryRadiusInput)
     filtered_results = self.filterByRadius(results, QueryRadiusInput)
     if QueryRadiusInput.sort == True:
         # Tuples list (distance to the center point, the point data returned from dynamoDB)
         tuples = []
         centerLatLng = S2LatLng.from_degrees(
             QueryRadiusInput.getCenterPoint().getLatitude(),
             QueryRadiusInput.getCenterPoint().getLongitude())
         for item in filtered_results:
             geoJson = item[self.config.geoJsonAttributeName]["S"]
             coordinates = geoJson.split(",")
             latitude = float(coordinates[0])
             longitude = float(coordinates[1])
             latLng = S2LatLng.from_degrees(latitude, longitude)
             tuples.append((centerLatLng.get_distance(latLng).radians *
                            EARTH_RADIUS_METERS, item))
         tuples.sort(key=lambda x: x[0]
                     )  # Sort the list by distance (x [0] is the distance)
         return [item[1] for item in tuples]
     else:
         return filtered_results
Example #4
0
def cover_region_s2(location1,location2):
    rc = RegionCoverer()
    rc.max_level = lvl_big
    rc.min_level = lvl_big
    rc.max_cells = 1000
    locations = []

    if location1[0] > location2[0]:
        lat1,lat2 = location2[0],location1[0]
    else:
        lat1, lat2 = location1[0], location2[0]


    if location1[1] > location2[1]:
        lng1, lng2 = location2[1], location1[1]
    else:
        lng1, lng2 = location1[1], location2[1]

    lng1 = (lng1 + 180) % 360 - 180
    lng2 = (lng2 + 180) % 360 - 180

    lngs = []
    if lng2 > lng1:
        lngs.append((lng1,lng2))
    elif lng2 < lng1:
        lngs.append((-180.0,lng2))
        lngs.append((lng1,180.0))

    for lng1,lng2 in lngs:
        cids = rc.get_covering(LatLngRect(LatLng.from_degrees(lat1,lng1),LatLng.from_degrees(lat2,lng2)))

        for cid in cids:
            ll_cid = cid.to_lat_lng()
            locations.append((ll_cid.lat().degrees,ll_cid.lng().degrees))
    return locations
Example #5
0
def s2_to_geo_boundary(s2_address, geo_json_conformant=False):
    """Boundaries of given s2 square
    
    Parameters
    ----------
    s2_address : string
        Unique s2 token
    geo_json : bool, optional
        If True, output coordinates is geo_json conformant (lng, lat)
        If False, coordinates are (lat, lng), by default False
    
    Returns
    -------
    list
        Geometry of given s2 square
    """

    cell = _token_to_cell(s2_address)

    return [
        _to_lonlat(LatLng.from_point(cell.get_vertex(i)))
        for i in [0, 1, 2, 3, 0]
    ] if geo_json_conformant else [
        _to_latlon(LatLng.from_point(cell.get_vertex(i)))
        for i in [0, 1, 2, 3]
    ]
Example #6
0
    def compute_circle(center: s2sphere.LatLng,
                       radius_km: float) -> typing.Iterator[s2sphere.LatLng]:
        """Compute a circle with given center and radius

        :param center: Center of the circle
        :param radius_km: Radius of the circle
        :type center: s2sphere.LatLng
        :type radius_km: float

        :return: circle
        :rtype: typing.Iterator[s2sphere.LatLng]
        """
        first = None
        delta_angle = 0.1
        angle = 0.0
        geod = Geodesic.WGS84
        while angle < 360.0:
            d = geod.Direct(
                center.lat().degrees,
                center.lng().degrees,
                angle,
                radius_km * 1000.0,
                Geodesic.LONGITUDE | Geodesic.LATITUDE | Geodesic.LONG_UNROLL,
            )
            latlng = create_latlng(d["lat2"], d["lon2"])
            if first is None:
                first = latlng
            yield latlng
            angle = angle + delta_angle
        if first:
            yield first
Example #7
0
def neighbor_s2_circle(
        location,
        i_dir=0.0,
        j_dir=0.0):  # input location can be list, tuple or Point
    if type(location) in (list, tuple):
        ll_location = LatLng.from_degrees(location[0], location[1])
    elif type(location) is Point:
        ll_location = LatLng.from_point(location)
    elif type(location) is LatLng:
        ll_location = location
    else:
        return None

    cid_large = CellId.from_lat_lng(ll_location).parent(lvl_big)

    cid_small = cid_large.child_begin(lvl_small)
    vec_to_j = (Cell(ij_offs(cid_small, 0, 1)).get_center() -
                Cell(cid_small).get_center()).normalize()
    vec_to_i = (Cell(ij_offs(cid_small, 1, 0)).get_center() -
                Cell(cid_small).get_center()).normalize()

    vec_newlocation = ll_location.to_point() + safety * HEX_R / earth_Rrect * (
        i_dir * 3**0.5 * vec_to_i + j_dir * 1.5 * vec_to_j)

    return vec_newlocation  # output is Point
Example #8
0
    def locate_step(self, location):
        (lat, lon) = location
        origin = LatLng.from_degrees(lat, lon)
        parent = CellId.from_lat_lng(origin).parent(15)
        h = self.niantic.heartbit(location)
        hs = [h]

        for child in parent.children():
            latlng = LatLng.from_point(Cell(child).get_center())
            child_location = (latlng.lat().degrees, latlng.lng().degrees)
            hs.append(self.niantic.heartbit(child_location))

        visible = self.__parse_pokemons(hs)

        current_time_ms = int(round(time.time() * 1000))
        for poke in visible.values():
            pokeid = str(poke.pokemon.PokemonId)
            pokename = POKEMON_NAMES[pokeid]
            expires = poke.LastModifiedMs + poke.TimeTillHiddenMs

            self.data.pokemons[poke.SpawnPointId] = {
                "lat": poke.Latitude,
                "lng": poke.Longitude,
                "expires": expires,
                'expiresAfter': (expires - current_time_ms) / 1000,
                "id": poke.pokemon.PokemonId,
                "name": pokename
            }
        logger.debug('-- step {} {}: found {} pokemons, {} pokestops, {} gyms'.format(
            lat, lon,
            len(self.data.pokemons), len(self.data.pokestops), len(self.data.gyms)))
Example #9
0
File: geo.py Project: interuss/dss
def unflatten(reference: s2sphere.LatLng,
              point: Tuple[float, float]) -> s2sphere.LatLng:
    """Locally unflatten a (dx, dy) point to an absolute lat-lng point."""
    return s2sphere.LatLng.from_degrees(
        reference.lat().degrees + point[1] * 360 /
        (EARTH_CIRCUMFERENCE_KM * 1000),
        reference.lng().degrees + point[0] * 360 /
        (EARTH_CIRCUMFERENCE_KM * 1000 * math.cos(reference.lat().radians)))
Example #10
0
    def list_pokemon(self):
        # todo: Check if client is Android/iOS/Desktop for geolink, currently
        # only supports Android.
        pokemon_list = []

        # Allow client to specify location.
        lat = request.args.get('lat', self.current_location[0], type=float)
        lon = request.args.get('lon', self.current_location[1], type=float)
        origin_point = LatLng.from_degrees(lat, lon)

        for pokemon in convert_pokemon_list(
                Pokemon.get_active(None, None, None, None)):
            pokemon_point = LatLng.from_degrees(pokemon['latitude'],
                                                pokemon['longitude'])
            diff = pokemon_point - origin_point
            diff_lat = diff.lat().degrees
            diff_lng = diff.lng().degrees
            direction = (('N' if diff_lat >= 0 else 'S')
                         if abs(diff_lat) > 1e-4 else '') +\
                        (('E' if diff_lng >= 0 else 'W')
                         if abs(diff_lng) > 1e-4 else '')
            entry = {
                'id':
                pokemon['pokemon_id'],
                'name':
                pokemon['pokemon_name'],
                'card_dir':
                direction,
                'distance':
                int(
                    origin_point.get_distance(pokemon_point).radians *
                    6366468.241830914),
                'time_to_disappear':
                '%d min %d sec' % (divmod(
                    (pokemon['disappear_time'] - datetime.utcnow()).seconds,
                    60)),
                'disappear_time':
                pokemon['disappear_time'],
                'disappear_sec':
                (pokemon['disappear_time'] - datetime.utcnow()).seconds,
                'latitude':
                pokemon['latitude'],
                'longitude':
                pokemon['longitude']
            }
            pokemon_list.append((entry, entry['distance']))
        pokemon_list = [y[0] for y in sorted(pokemon_list, key=lambda x: x[1])]
        args = get_args()
        visibility_flags = {
            'custom_css': args.custom_css,
            'custom_js': args.custom_js
        }

        return render_template('mobile_list.html',
                               pokemon_list=pokemon_list,
                               origin_lat=lat,
                               origin_lng=lon,
                               show=visibility_flags)
Example #11
0
 def get_cellid_center_coordinate(self, cellid):
     """
     get one cell's center point's coordinate [longitude, latitude]
     :param cellid: lnglat_to_cellid生成的cellid
     :return:tuple(center_longitude, center_latitude)
     """
     center = Cell(cell_id=CellId(cellid)).get_center()
     return (LatLng.longitude(center).degrees,
             LatLng.latitude(center).degrees)
Example #12
0
def main():
    origin_lat_i, origin_lng_i = f2i(origin_lat), f2i(origin_lng)
    api_endpoint, access_token, profile_response = login(origin_lat_i, origin_lng_i)

    with sqlite3.connect('database.db') as db:
        create_tables(db)

    while True:
        pos = 1
        x = 0
        y = 0
        dx = 0
        dy = -1
        steplimit2 = steplimit**2
        for step in range(steplimit2):
            #print('looping: step {} of {}'.format(step + 1, steplimit**2))
            # Scan location math
            if -steplimit2 / 2 < x <= steplimit2 / 2 and -steplimit2 / 2 < y <= steplimit2 / 2:
                step_lat = x * 0.0025 + origin_lat
                step_lng = y * 0.0025 + origin_lng
                step_lat_i = f2i(step_lat)
                step_lng_i = f2i(step_lng)
            if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
                (dx, dy) = (-dy, dx)

            (x, y) = (x + dx, y + dy)

            #print('[+] Searching for Pokemon at location {} {}'.format(step_lat, step_lng))
            origin = LatLng.from_degrees(step_lat, step_lng)
            parent = CellId.from_lat_lng(origin).parent(15)
            h = get_heartbeat(api_endpoint, access_token, profile_response, step_lat, step_lng, step_lat_i, step_lng_i)
            hs = [h]

            for child in parent.children():
                latlng = LatLng.from_point(Cell(child).get_center())
                child_lat, child_lng = latlng.lat().degrees, latlng.lng().degrees
                child_lat_i, child_lng_i = f2i(child_lat), f2i(child_lng)
                hs.append(get_heartbeat(api_endpoint, access_token, profile_response, child_lat, child_lng, child_lat_i, child_lng_i))
            visible = []

            data = []
            for hh in hs:
                for cell in hh.cells:
                    for poke in cell.WildPokemon:
                        disappear_ms = cell.AsOfTimeMs + poke.TimeTillHiddenMs
                        data.append((
                            poke.SpawnPointId,
                            poke.pokemon.PokemonId,
                            poke.Latitude,
                            poke.Longitude,
                            disappear_ms,
                        ))
            if data:
                print('Upserting {} pokemon'.format(len(data)))
                with sqlite3.connect('database.db') as db:
                    insert_data(db, data)
Example #13
0
def get_cardinal_dir(pt_a, pt_b):
    if len(pt_b) < 2:
        return '?'
    origin_point = LatLng.from_degrees(*pt_b)
    lat_lng = LatLng.from_degrees(*pt_a)
    diff = lat_lng - origin_point
    diff_lat = diff.lat().degrees
    diff_lng = diff.lng().degrees
    direction = (('N' if diff_lat >= 0 else 'S') if abs(diff_lat) > 1e-4 else '') + \
                (('E' if diff_lng >= 0 else 'W') if abs(diff_lng) > 1e-4 else '')
    return direction
Example #14
0
def get_dir(lat, lng):
	origin_point = config.get("LOCATION")
	if origin_point is None:
		return "NoLocationSet" #No location set
	origin_point = LatLng.from_degrees(origin_point[0], origin_point[1])
	latLon = LatLng.from_degrees(lat, lng)
	diff = latLon - origin_point
	diff_lat = diff.lat().degrees
	diff_lng = diff.lng().degrees
	direction = (('N' if diff_lat >= 0 else 'S') if abs(diff_lat) > 1e-4 else '') + \
		(('E' if diff_lng >= 0 else 'W') if abs(diff_lng) > 1e-4 else '')
	return direction
Example #15
0
def get_dir(lat, lng):
    origin_point = config.get("LOCATION")
    if origin_point is None:
        return "NoLocationSet"  #No location set
    origin_point = LatLng.from_degrees(origin_point[0], origin_point[1])
    latLon = LatLng.from_degrees(lat, lng)
    diff = latLon - origin_point
    diff_lat = diff.lat().degrees
    diff_lng = diff.lng().degrees
    direction = (('N' if diff_lat >= 0 else 'S') if abs(diff_lat) > 1e-4 else '') + \
     (('E' if diff_lng >= 0 else 'W') if abs(diff_lng) > 1e-4 else '')
    return direction
Example #16
0
def bounds(cell_id):
    cell = Cell(cell_id)

    url_string = 'http://maps.googleapis.com/maps/api/staticmap?size=400x400&path='

    coords = []
    for i in range(4) + [0]:
        point = cell.get_vertex(i)
        coords.append("{},{}".format(LatLng.latitude(point).degrees, LatLng.longitude(point).degrees))

    url_string += "|".join(coords)
    print url_string
Example #17
0
 def adjust(cls, time: datetime.datetime,
            latlng: s2sphere.LatLng) -> datetime.datetime:
     # If a timezone is set, there's nothing to do.
     if time.utcoffset():
         return time
     assert cls._timezonefinder
     # if tz_name name is None set it to UTC
     tz_name = cls._timezonefinder.timezone_at(
         lat=latlng.lat().degrees, lng=latlng.lng().degrees) or "UTC"
     tz = pytz.timezone(tz_name)
     tz_time = time.astimezone(tz)
     return tz_time
Example #18
0
    def mercator(latlng: s2sphere.LatLng) -> typing.Tuple[float, float]:
        """Mercator projection

        :param latlng: LatLng object
        :type latlng: s2sphere.LatLng
        :return: tile values of given LatLng
        :rtype: tuple
        """
        lat = latlng.lat().radians
        lng = latlng.lng().radians
        return lng / (2 * math.pi) + 0.5, (
            1 - math.log(math.tan(lat) + (1 / math.cos(lat))) / math.pi) / 2
Example #19
0
def cover_square(lat, lng, width, level=15):
    offset = int(width / 2)
    g = Geodesic.WGS84  # @UndefinedVariable
    r = RegionCoverer()
    r.min_level, r.min_level = level, level
    g1 = g.Direct(lat, lng, 360, offset)
    g1 = g.Direct(g1['lat2'], g1['lon2'], 270, offset)
    p1 = LatLng.from_degrees(g1['lat2'], g1['lon2'])
    g2 = g.Direct(lat, lng, 180, offset)
    g2 = g.Direct(g2['lat2'], g2['lon2'], 90, offset)
    p2 = LatLng.from_degrees(g2['lat2'], g2['lon2'])
    cells = r.get_covering(LatLngRect.from_point_pair(p1, p2))
    return cells
Example #20
0
 def latLngRectFromQueryRectangleInput(
         self, QueryRectangleRequest: 'QueryRectangleRequest'):
     queryRectangleRequest = QueryRectangleRequest
     minPoint = queryRectangleRequest.getMinPoint()
     maxPoint = queryRectangleRequest.getMaxPoint()
     latLngRect = None
     if minPoint is not None and maxPoint is not None:
         minLatLng = S2LatLng.from_degrees(minPoint.getLatitude(),
                                           minPoint.getLongitude())
         maxLatLng = S2LatLng.from_degrees(maxPoint.getLatitude(),
                                           maxPoint.getLongitude())
         latLngRect = S2LatLngRect.from_point_pair(minLatLng, maxLatLng)
     return latLngRect
Example #21
0
def cover_square(lat, lng, width, level=15):
    offset = int(width / 2)
    g = Geodesic.WGS84  # @UndefinedVariable
    r = RegionCoverer()
    r.min_level, r.min_level = level, level
    g1 = g.Direct(lat, lng, 360, offset)
    g1 = g.Direct(g1['lat2'],g1['lon2'],270,offset)
    p1 = LatLng.from_degrees(g1['lat2'],g1['lon2'])
    g2 = g.Direct(lat, lng, 180, offset)
    g2 = g.Direct(g2['lat2'],g2['lon2'], 90,offset)
    p2 = LatLng.from_degrees(g2['lat2'],g2['lon2'])
    cells = r.get_covering(LatLngRect.from_point_pair(p1, p2))
    return cells
Example #22
0
    def get_pokemons(self):
        pokemon_list = []
        origin_point = LatLng.from_degrees(self.location.latitude, self.location.longitude)
        for pokemon in Pokemon.get_active():
            pokemon_point = LatLng.from_degrees(pokemon['latitude'], pokemon['longitude'])

            pokemon_list.append({
                'id': pokemon['pokemon_id'],
                'name': pokemon['pokemon_name'],
                'time': '%02d:%02d' % (divmod((pokemon['disappear_time'] - datetime.utcnow()).seconds, 60)),
                'latitude': pokemon['latitude'],
                'longitude': pokemon['longitude']
            })

        return pokemon_list
Example #23
0
 def getLatLongIndex(latitude, longitude):
     return CellId.from_lat_lng(
         LatLng.from_degrees(
             latitude,
             longitude
         )
     ).id()
Example #24
0
def getNeighbors(location):
    level = 15
    origin = CellId.from_lat_lng(LatLng.from_degrees(location[0], location[1])).parent(level)

    max_size = 1 << 30
    size = origin.get_size_ij(level)

    face, i, j = origin.to_face_ij_orientation()[0:3]

    walk = [origin.id(),
            origin.from_face_ij_same(face, i, j - size, j - size >= 0).parent(level).id(),
            origin.from_face_ij_same(face, i, j + size, j + size < max_size).parent(level).id(),
            origin.from_face_ij_same(face, i - size, j, i - size >= 0).parent(level).id(),
            origin.from_face_ij_same(face, i + size, j, i + size < max_size).parent(level).id(),
            origin.from_face_ij_same(face, i - size, j - size, j - size >= 0 and i - size >= 0).parent(level).id(),
            origin.from_face_ij_same(face, i + size, j - size, j - size >= 0 and i + size < max_size).parent(level).id(),
            origin.from_face_ij_same(face, i - size, j + size, j + size < max_size and i - size >= 0).parent(level).id(),
            origin.from_face_ij_same(face, i + size, j + size, j + size < max_size and i + size < max_size).parent(level).id()]
            #origin.from_face_ij_same(face, i, j - 2*size, j - 2*size >= 0).parent(level).id(),
            #origin.from_face_ij_same(face, i - size, j - 2*size, j - 2*size >= 0 and i - size >=0).parent(level).id(),
            #origin.from_face_ij_same(face, i + size, j - 2*size, j - 2*size >= 0 and i + size < max_size).parent(level).id(),
            #origin.from_face_ij_same(face, i, j + 2*size, j + 2*size < max_size).parent(level).id(),
            #origin.from_face_ij_same(face, i - size, j + 2*size, j + 2*size < max_size and i - size >=0).parent(level).id(),
            #origin.from_face_ij_same(face, i + size, j + 2*size, j + 2*size < max_size and i + size < max_size).parent(level).id(),
            #origin.from_face_ij_same(face, i + 2*size, j, i + 2*size < max_size).parent(level).id(),
            #origin.from_face_ij_same(face, i + 2*size, j - size, j - size >= 0 and i + 2*size < max_size).parent(level).id(),
            #origin.from_face_ij_same(face, i + 2*size, j + size, j + size < max_size and i + 2*size < max_size).parent(level).id(),
            #origin.from_face_ij_same(face, i - 2*size, j, i - 2*size >= 0).parent(level).id(),
            #origin.from_face_ij_same(face, i - 2*size, j - size, j - size >= 0 and i - 2*size >=0).parent(level).id(),
            #origin.from_face_ij_same(face, i - 2*size, j + size, j + size < max_size and i - 2*size >=0).parent(level).id()]
    return walk
Example #25
0
    def getCells(self, radius=10, bothDirections=True):
        origin = CellId.from_lat_lng(
            LatLng.from_degrees(
                self.latitude,
                self.longitude
            )
        ).parent(15)

        # Create walk around area
        walk = [origin.id()]
        right = origin.next()
        left = origin.prev()

        # Double the radius if we're only walking one way
        if not bothDirections:
            radius *= 2

        # Search around provided radius
        for _ in range(radius):
            walk.append(right.id())
            right = right.next()
            if bothDirections:
                walk.append(left.id())
                left = left.prev()

        # Return everything
        return sorted(walk)
Example #26
0
def makeWildPokemon(location):
    # Cause the randomness to only shift every N minutes (thus new pokes every N minutes)
    offset = int(time() % 3600) / 10
    seedid = str(location[0]) + str(location[1]) + str(offset)
    seed(seedid)

    # Now, collect the pokes for this can point
    pokes = []
    for i in range(randint(0, 2)):
        coords = getRandomPoint(location)
        ll = LatLng.from_degrees(coords[0], coords[1])
        cellId = CellId.from_lat_lng(ll).parent(20).to_token()
        pokes.append({
            'encounter_id': 'pkm' + seedid + str(i),
            'last_modified_timestamp_ms': int((time() - 10) * 1000),
            'latitude': coords[0],
            'longitude': coords[1],
            'pokemon_data': {
                'pokemon_id': randint(1, 140),
                'iv_attack': 999999
            },
            'spawn_point_id': cellId,
            'time_till_hidden_ms': randint(60, 600) * 1000
        })
    return pokes
Example #27
0
    async def _send_weather_webhook(self, s2cellId, weatherId, severe, warn, day, time):
        if self.__application_args.weather_webhook:
            log.debug("Send Weather Webhook")

            cell = Cell(CellId(s2cellId))
            coords = []
            for v in range(0, 4):
                vertex = LatLng.from_point(cell.get_vertex(v))
                coords.append([vertex.lat().degrees, vertex.lng().degrees])

            data = weather_webhook_payload.format(s2cellId, coords, weatherId, severe, warn, day, time)

            log.debug(data)
            payload = json.loads(data)
            log.info("Sending weather webhook: %s" % str(payload))
            try:
                response = requests.post(
                    self.__application_args.webhook_url, data=json.dumps(payload),
                    headers={'Content-Type': 'application/json'},
                    timeout=5
                )
                if response.status_code != 200:
                    log.warning("Go status code other than 200 OK from webhook destination: %s" % str(response.status_code))
                else:
                    log.info("Success sending webhook")
            except Exception as e:
                log.warning("Exception occured while sending webhook: %s" % str(e))
        else:
            log.debug("Weather Webhook Disabled")
Example #28
0
    def writeplans():
        subplans = request.args.get('subplans', type=int)
        plans = []
        lock_plans.acquire()
        for token in list_plans:
            center = LatLng.from_point(
                Cell(CellId.from_token(token)).get_center())
            center = (center.lat().degrees, center.lng().degrees)
            for ind_sub in range(1, subplans + 1):
                plans.append({
                    'type': 'seikur0_s2',
                    'token': token,
                    'location': [center[0], center[1]],
                    'subplans': subplans,
                    'subplan_index': ind_sub
                })
        lock_plans.release()

        for plan in plans:
            filename = '{}_{}_{}.plan'.format(plan['token'],
                                              plan['subplan_index'],
                                              plan['subplans'])
            try:
                f = open(plandir + '/' + filename, 'w', 0)
                json.dump(plan, f, indent=1, separators=(',', ': '))
                print('[+] Plan file {} was written.'.format(filename))
            except Exception as e:
                print(
                    '[+] Error while writing plan file, error : {}'.format(e))
            finally:
                if 'f' in vars() and not f.closed:
                    f.close()

        return jsonify("")
Example #29
0
    def getCells(self, radius=10, bothDirections=True):
        origin = CellId.from_lat_lng(
            LatLng.from_degrees(
                self.latitude,
                self.longitude
            )
        ).parent(15)

        # Create walk around area
        walk = [origin.id()]
        right = origin.next()
        left = origin.prev()

        # Double the radius if we're only walking one way
        if not bothDirections:
            radius *= 2

        # Search around provided radius
        for _ in range(radius):
            walk.append(right.id())
            right = right.next()
            if bothDirections:
                walk.append(left.id())
                left = left.prev()

        # Return everything
        return sorted(walk)
Example #30
0
 def getLatLongIndex(latitude, longitude):
     return CellId.from_lat_lng(
         LatLng.from_degrees(
             latitude,
             longitude
         )
     ).id()
Example #31
0
 def getCellId(self):
     return CellId.from_lat_lng(
         LatLng.from_degrees(
             self.latitude,
             self.longitude
         )
     ).parent(15)
Example #32
0
    def on_msg_published(self, message):
        msg = json.loads(str(message))
        '''
        v_id = msg["v_id"]
        if(self.vid != v_id):
	    log.msg("Got data that i did not subscribe, or subscribed earlier")
	    #ToDo: unsubscribe v_id
	    return
        '''
	if(self.is_heartbeat):
            log.msg("Heartbeat notification returing")
            return
	if(self.is_live):
            log.msg("Publishing live location to ", self.uid)
            self.sendMessage(str(message))
	if(self.is_notification):
            loc = cyclone.escape.json_decode(message)
            log.msg("Sending the notification:%r" % self.uid)
            vlat = loc["latitude"]
            vlon = loc["longitude"]
            ulat = "12.8379176"
            ulon = "77.6391782"

            '''
            #Inside websocket not able to query on db so hardcoding the ulat and ulon
            rs = yield self.users.find({"_id": self.uid})
            if len(rs):
                ulat = rs["l_lattitude"]
                ulon = rs["l_longitude"]
                if(len(ulat)):
                    log.msg("Last lattitude available")
                else:
                    log.msg("Last lattitude not available taking default value")
                    ulat = "12.8379176"
                    ulon = "77.6391782"
            else:
                log.msg("uid is not available")
            '''
            log.msg("vlat:%r vlon:%r ulat:%r ulon:%r" % (vlat, vlon, ulat, ulon))
            distance = LatLng.from_degrees(float(vlat), float(vlon)).get_distance(LatLng.from_degrees(float(ulat), float(ulon))).radians
            distance = distance * 6371
            resp = {"resp_code": True,
                    "type": "distance",
                    "data": distance
                   }
            log.msg(resp)
            self.sendMessage(str(resp))
Example #33
0
def update_missing_s2_ids():
    log.info("Looking for spawn points with missing s2 coordinates")
    for spawnpoint in db_load_spawn_points_missing_s2():
        latlng = LatLng.from_degrees(spawnpoint["latitude"],
                                     spawnpoint["longitude"])
        cell = CellId.from_lat_lng(latlng).parent(15)
        db_set_s2_cellid(spawnpoint["id"], cell.id())
    log.info("Done establishing s2 points")
Example #34
0
 def filterByRadius(self, ItemList: 'points retrieved from dynamoDB',
                    QueryRadiusInput: 'QueryRadiusRequest'):
     centerLatLng = S2LatLng.from_degrees(
         QueryRadiusInput.getCenterPoint().getLatitude(),
         QueryRadiusInput.getCenterPoint().getLongitude())
     radiusInMeter = QueryRadiusInput.getRadiusInMeter()
     result = []
     for item in ItemList:
         geoJson = item[self.config.geoJsonAttributeName]["S"]
         coordinates = geoJson.split(",")
         latitude = float(coordinates[0])
         longitude = float(coordinates[1])
         latLng = S2LatLng.from_degrees(latitude, longitude)
         if (centerLatLng.get_distance(latLng).radians * EARTH_RADIUS_METERS
                 < radiusInMeter):
             result.append(item)
     return result
Example #35
0
def _bbox_polyfill(
    geo_json,
    res,
):
    """returns list of S2 ids"""

    lat, lon = _geo_json_to_extremes(geo_json)

    p1 = LatLng.from_degrees(min(lat), min(lon))
    p2 = LatLng.from_degrees(max(lat), max(lon))

    region = LatLngRect.from_point_pair(p1, p2)

    coverer = RegionCoverer()
    coverer.min_level = res
    coverer.max_level = res
    return coverer.get_covering(region)
Example #36
0
def get_s2_cell_center(lat, lng, level):
    lat_lng = LatLng.from_degrees(lat, lng)
    cell_id = CellId.from_lat_lng(lat_lng).parent(level)
    center = cell_id.to_lat_lng()
    return {
        'lat': float(center.lat().degrees),
        'lon': float(center.lng().degrees)
    }
Example #37
0
def cover_circle(lat, lng, radius, level):
    EARTH_RADIUS = 6371 * 1000
    region = Cap.from_axis_angle(LatLng.from_degrees(lat, lng).to_point(), \
                                 Angle.from_degrees(360*radius/(2*math.pi*EARTH_RADIUS)))
    coverer = RegionCoverer()
    coverer.min_level = level
    coverer.max_level = level
    cells = coverer.get_covering(region)
    return cells
Example #38
0
def sub_cell(cell,i=0,dist=25):
    
    g = Geodesic.WGS84  # @UndefinedVariable
    olat = CellId.to_lat_lng(cell).lat().degrees
    olng = CellId.to_lat_lng(cell).lng().degrees

    p = g.Direct(olat, olng,(45+(90*i)),dist)
    c = CellId.from_lat_lng(LatLng.from_degrees(p['lat2'],p['lon2']))
    
    return c.parent(cell.level()+1)
Example #39
0
    def remove_plan():
        location = (request.args.get('lat', type=float), request.args.get('lng', type=float))
        cid = CellId.from_lat_lng(LatLng.from_degrees(location[0],location[1])).parent(mapl.lvl_big)
        token = cid.to_token()

        lock_plans.acquire()
        if token in list_plans:
            list_plans.pop(list_plans.index(token))
        lock_plans.release()
        return jsonify("")
Example #40
0
def cover_circle(lat, lng, radius, level=15):
    EARTH = 6371000
    region = Cap.from_axis_angle(\
             LatLng.from_degrees(lat, lng).to_point(), \
             Angle.from_degrees(360*radius/(2*math.pi*EARTH)))
    coverer = RegionCoverer()
    coverer.min_level = level
    coverer.max_level = level
    cells = coverer.get_covering(region)
    return cells
Example #41
0
def neighbor_s2_circle(location, i_dir=0.0, j_dir=0.0):  # input location can be list, tuple or Point
    if type(location) in (list, tuple):
        ll_location = LatLng.from_degrees(location[0], location[1])
    elif type(location) is Point:
        ll_location = LatLng.from_point(location)
    elif type(location) is LatLng:
        ll_location = location
    else:
        return None

    cid_large = CellId.from_lat_lng(ll_location).parent(lvl_big)

    cid_small = cid_large.child_begin(lvl_small)
    vec_to_j = (Cell(ij_offs(cid_small, 0, 1)).get_center() - Cell(cid_small).get_center()).normalize()
    vec_to_i = (Cell(ij_offs(cid_small, 1, 0)).get_center() - Cell(cid_small).get_center()).normalize()

    vec_newlocation = ll_location.to_point() + safety * HEX_R / earth_Rrect * (i_dir * 3 ** 0.5 * vec_to_i + j_dir * 1.5 * vec_to_j)

    return vec_newlocation  # output is Point
Example #42
0
def sub_cell(cell,i=0,dist=25):
    
    g = Geodesic.WGS84  # @UndefinedVariable
    olat = CellId.to_lat_lng(cell).lat().degrees
    olng = CellId.to_lat_lng(cell).lng().degrees

    p = g.Direct(olat, olng,(45+(90*i)),dist)
    c = CellId.from_lat_lng(LatLng.from_degrees(p['lat2'],p['lon2']))
    
    return c.parent(cell.level()+1)
Example #43
0
def get_cell_walk(lat, lng, radius, level=15):
    origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(level)
    walk = [origin]
    right = origin.next()
    left = origin.prev()
    for dummy in range(radius):
        walk.append(right)
        walk.append(left)
        right = right.next()
        left = left.prev()
    return sorted(walk)
Example #44
0
def get_cell_walk(lat, lng, radius, level=15):
    origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(level)
    walk = [origin]
    right = origin.next()
    left = origin.prev()
    for dummy in range(radius):
        walk.append(right)
        walk.append(left)
        right = right.next()
        left = left.prev()
    return sorted(walk)
Example #45
0
def get_cell_ids(lat, long, radius=500):
    if radius > 500:
        radius = 500
    region = Cap.from_axis_angle(
        LatLng.from_degrees(lat, long).to_point(),
        Angle.from_degrees(360 * radius / (2 * math.pi * EARTH_RADIUS)))
    coverer = RegionCoverer()
    coverer.min_level = 15
    coverer.max_level = 15
    cells = coverer.get_covering(region)
    cells = cells[:21]
    return sorted([x.id() for x in cells])
Example #46
0
def get_cellid(lat, long):
    origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15)
    walk = [origin.id()]

    next = origin.next()
    prev = origin.prev()
    for i in range(10):
        walk.append(prev.id())
        walk.append(next.id())
        next = next.next()
        prev = prev.prev()
    return sorted(walk)
Example #47
0
def get_cell_ids(lat, long, radius=1000):
    # Max values allowed by server according to this comment:
    # https://github.com/AeonLucid/POGOProtos/issues/83#issuecomment-235612285
    if radius > 1500:
        radius = 1500  # radius = 1500 is max allowed by the server
    region = Cap.from_axis_angle(LatLng.from_degrees(lat, long).to_point(), Angle.from_degrees(360*radius/(2*math.pi*EARTH_RADIUS)))
    coverer = RegionCoverer()
    coverer.min_level = 15
    coverer.max_level = 15
    cells = coverer.get_covering(region)
    cells = cells[:100]  # len(cells) = 100 is max allowed by the server
    return sorted([x.id() for x in cells])
Example #48
0
 def add_plan():
     location = (request.args.get('lat', type=float),request.args.get('lng', type=float))
     all_loc,border,cid = mapl.get_area_cell(location,True)
     # grid = mapl.Hexgrid()
     # all_loc = grid.cover_cell(cid)
     center = LatLng.from_point(Cell(cid).get_center())
     center = (center.lat().degrees, center.lng().degrees)
     token = cid.to_token()
     lock_plans.acquire()
     list_plans.append(token)
     lock_plans.release()
     return jsonify((all_loc, border,[center,token],[]))
Example #49
0
def get_cellid(lat, lng, level=15):
    origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(level)
    walk = [origin.id()]

    # 10 before and 10 after
    next = origin.next()
    prev = origin.prev()
    for i in range(10):
        walk.append(prev.id())
        walk.append(next.id())
        next = next.next()
        prev = prev.prev()
    return sorted(walk)
Example #50
0
def get_neighbors(lat, lng):
    origin = CellId.from_lat_lng(LatLng.from_degrees(lat, lng)).parent(15)
    walk = [origin.id()]

    # 10 before and 10 after
    next = origin.next()
    prev = origin.prev()
    for i in range(10):
        walk.append(prev.id())
        walk.append(next.id())
        next = next.next()
        prev = prev.prev()
    return walk
Example #51
0
    def list_pokemon(self):
        # todo: check if client is android/iOS/Desktop for geolink, currently
        # only supports android
        pokemon_list = []

        # Allow client to specify location
        lat = request.args.get('lat', self.current_location[0], type=float)
        lon = request.args.get('lon', self.current_location[1], type=float)
        origin_point = LatLng.from_degrees(lat, lon)

        for pokemon in Pokemon.get_active(None, None, None, None):
            pokemon_point = LatLng.from_degrees(pokemon['latitude'],
                                                pokemon['longitude'])
            diff = pokemon_point - origin_point
            diff_lat = diff.lat().degrees
            diff_lng = diff.lng().degrees
            direction = (('N' if diff_lat >= 0 else 'S')
                         if abs(diff_lat) > 1e-4 else '') +\
                        (('E' if diff_lng >= 0 else 'W')
                         if abs(diff_lng) > 1e-4 else '')
            entry = {
                'id': pokemon['pokemon_id'],
                'name': pokemon['pokemon_name'],
                'card_dir': direction,
                'distance': int(origin_point.get_distance(
                    pokemon_point).radians * 6366468.241830914),
                'time_to_disappear': '%d min %d sec' % (divmod((
                    pokemon['disappear_time'] - datetime.utcnow()).seconds, 60)),
                'disappear_time': pokemon['disappear_time'],
                'disappear_sec': (pokemon['disappear_time'] - datetime.utcnow()).seconds,
                'latitude': pokemon['latitude'],
                'longitude': pokemon['longitude']
            }
            pokemon_list.append((entry, entry['distance']))
        pokemon_list = [y[0] for y in sorted(pokemon_list, key=lambda x: x[1])]
        return render_template('mobile_list.html',
                               pokemon_list=pokemon_list,
                               origin_lat=lat,
                               origin_lng=lon)
Example #52
0
    def _get_cellid(self, lat, long, radius=10):
        origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15)
        walk = [origin.id()]

        # 10 before and 10 after
        next = origin.next()
        prev = origin.prev()
        for i in range(radius):
            walk.append(prev.id())
            walk.append(next.id())
            next = next.next()
            prev = prev.prev()
        return sorted(walk)
Example #53
0
def get_cellid(lat, long):
    origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15)
    walk = [origin.id()]

    # 10 before and 10 after
    next = origin.next()
    prev = origin.prev()
    for i in range(10):
        walk.append(prev.id())
        walk.append(next.id())
        next = next.next()
        prev = prev.prev()
    return ''.join(map(encode, sorted(walk)))
Example #54
0
def cell_spiral(lat, lng, dist, level=15, step=100, res=3.6):
    cells = []

    g = Geodesic.WGS84  # @UndefinedVariable
    
    for i in xrange(0,dist,step):
        for rad in xrange(int(360/res)):
            p = g.Direct(lat, lng, rad*res, i)
            c = CellId.from_lat_lng(LatLng.from_degrees(p['lat2'],p['lon2']))
            c = c.parent(level)
            if c not in cells: cells.append(c)
    
    return cells
Example #55
0
    def _get_cell_id_from_latlong(self, radius=10):
        position_lat, position_lng, _ = self.api.get_position()
        origin = CellId.from_lat_lng(LatLng.from_degrees(i2f(position_lat), i2f(position_lng))).parent(15)
        walk = [origin.id()]

        # 10 before and 10 after
        next_cell = origin.next()
        prev_cell = origin.prev()
        for _ in range(radius):
            walk.append(prev_cell.id())
            walk.append(next_cell.id())
            next_cell = next_cell.next()
            prev_cell = prev_cell.prev()
        return sorted(walk)
Example #56
0
def get_cell_ids(lat, long, radius = 10):
	origin = CellId.from_lat_lng(LatLng.from_degrees(lat, long)).parent(15)
	walk = [origin.id()]
	right = origin.next()
	left = origin.prev()
	# Search around provided radius
	for i in range(radius):
		walk.append(right.id())
		walk.append(left.id())
		right = right.next()
		left = left.prev()

	# Return everything
	return sorted(walk)
Example #57
0
    def cover_cell(self, cid):
        lats = []
        lngs = []
        output = []
        s2_cell = Cell(cid)
        lvl = s2_cell.level()
        for i in [0, 1]:
            for j in [0, 1]:
                lats.append(s2_cell.get_latitude(i, j)/pi*180)
                lngs.append(s2_cell.get_longitude(i, j)/pi*180)
        locations = self.cover_region((min(lats),min(lngs)),(max(lats),max(lngs)))
        for location in locations:
            testid = CellId.from_lat_lng(LatLng.from_degrees(location[0],location[1])).parent(lvl)
            if testid == cid:
                output.append(location)

        return output
Example #58
0
    def get_meta_cell(self):
        location = self.position[0:2]
        cells = self.find_close_cells(*location)

        # Combine all cells into a single dict of the items we care about.
        forts = []
        wild_pokemons = []
        catchable_pokemons = []
        nearby_pokemons = []
        for cell in cells:
            if "forts" in cell and len(cell["forts"]):
                forts += cell["forts"]
            if "wild_pokemons" in cell and len(cell["wild_pokemons"]):
                wild_pokemons += cell["wild_pokemons"]
            if "catchable_pokemons" in cell and len(cell["catchable_pokemons"]):
                catchable_pokemons += cell["catchable_pokemons"]
            if "nearby_pokemons" in cell and len(cell["nearby_pokemons"]):
                latlng = LatLng.from_point(Cell(CellId(cell["s2_cell_id"])).get_center())

                for p in cell["nearby_pokemons"]:
                    p["latitude"] = latlng.lat().degrees
                    p["longitude"] = latlng.lng().degrees
                    p["s2_cell_id"] = cell["s2_cell_id"]

                nearby_pokemons += cell["nearby_pokemons"]

        # If there are forts present in the cells sent from the server or we don't yet have any cell data, return all data retrieved
        if len(forts) > 1 or not self.cell:
            return {
                "forts": forts,
                "wild_pokemons": wild_pokemons,
                "catchable_pokemons": catchable_pokemons,
                "nearby_pokemons": nearby_pokemons
            }
        # If there are no forts present in the data from the server, keep our existing fort data and only update the pokemon cells.
        else:
            return {
                "forts": self.cell["forts"],
                "wild_pokemons": wild_pokemons,
                "catchable_pokemons": catchable_pokemons,
                "nearby_pokemons": nearby_pokemons
            }
Example #59
0
def build_cap_coverage(lat, lng, cell_count=21, radius=100.0):
    # these are the zoom levels for s2cells
    min_zoom_level = 15
    max_zoom_level = 30

    # radius of the earth in meters
    R = 6378137.0;

    cap_height = ((radius/R)**2)/2
    axis = LatLng.from_degrees(lat, lng).to_point()
    cap = Cap.from_axis_height(axis, cap_height)

    coverer = RegionCoverer()
    coverer.min_level = min_zoom_level
    coverer.max_level = max_zoom_level
    coverer.max_cells = cell_count
    covering = list(coverer.get_covering(cap))
    while(len(covering) < cell_count):
        covering.append(covering[-1].next())
    return covering
Example #60
0
    def get_search_points(self, cell_id):
        points = []

        # For cell level 15
        for c in Cell(CellId(cell_id)).subdivide():
            for cc in c.subdivide():
                latlng = LatLng.from_point(cc.get_center())
                point = (latlng.lat().degrees, latlng.lng().degrees)
                points.append(point)

        points[0], points[1] = points[1], points[0]
        points[14], points[15] = points[15], points[14]
        point = points.pop(2)
        points.insert(7, point)
        point = points.pop(13)
        points.insert(8, point)

        closest = min(points, key=lambda p: great_circle(self.bot.position, p).meters)
        index = points.index(closest)

        return points[index:] + points[:index]