Ejemplo n.º 1
0
def getRSSIMax():
    """ fonction who search in the DB the best signal reception and despaly it in the map"""

    m = StaticMap(largeur,
                  hauteur,
                  url_template='http://a.tile.osm.org/{z}/{x}/{y}.png')
    cursor.execute("""SELECT max(RSSI) FROM coord """)
    rssi = cursor.fetchone()
    print rssi
    cursor.execute(
        """SELECT e_lat, e_long, s_lat, s_long, distance, SNR FROM coord WHERE RSSI=?""",
        rssi)
    coord = cursor.fetchone()  #getGPS()
    print coord

    lat_E, long_E, lat_S, long_S = coord[0], coord[1], coord[2], coord[3]
    m.add_line(Line(((long_S, lat_S), (long_E, lat_E)), 'blue', 3))

    icon_flag_1 = IconMarker((long_E, lat_E), 'icon/icon-flag.png', 12, 32)
    m.add_marker(icon_flag_1)
    icon_flag_2 = IconMarker((long_S, lat_S), 'icon/icon-flag.png', 12, 32)
    m.add_marker(icon_flag_2)

    global image
    image = m.render()
    image.save('map/RSSIMaxMap.png')
    image = PhotoImage(file='map/RSSIMaxMap.png')
    canvas.create_image(0, 0, image=image, anchor=NW)

    latLabel.configure(text=coord[0])
    longLabel.configure(text=coord[1])
    distenceLabel.configure(text=coord[4])

    rssiLabel.configure(text=coord[4])
    snrLabel.configure(text=coord[5])
Ejemplo n.º 2
0
def make_map(filename_without_ext,
             addresses,
             gmic_effect="fx_freaky_bw 90,20,0,0,0,0",
             no_display=False,
             prefix="LETTER"):
    m = StaticMap(800, 600, 80)
    g = gmic.Gmic("update")
    locator = Nominatim(user_agent="BerlinWallBreaker Agent")
    print("geocoding..")
    for address in addresses:
        loc = locator.geocode(address)
        icon_flag = IconMarker((loc.longitude, loc.latitude),
                               './samples/icon-flag.png', 12, 32)
        m.add_marker(icon_flag)
        print(loc)

    image = m.render()
    output_filename1 = prefix + filename_without_ext + "_original.png"
    output_filename2 = prefix + filename_without_ext + ".png"
    image.save(output_filename1)
    print(output_filename1)
    if not no_display:
        g.run(output_filename1 + " display")
    if "_fx_stylize" in gmic_effect:
        gmic.run(output_filename1 + " " + gmic_effect + " output[2] " +
                 output_filename2 + (" display[2]" if not no_display else ""))
    else:
        gmic.run(output_filename1 + " " + gmic_effect + " output " +
                 output_filename2 + (" display" if not no_display else ""))
    print(output_filename2)

    return output_filename1, output_filename2
Ejemplo n.º 3
0
def route(G, name_file, addresses):
    coords = addressesTOcoordinates(addresses)
    coord_origin, coord_destination = coords
    G_coord = create_G_Coord(G, coord_origin, coord_destination)
    #Application of djijstra algorithm with the graph correctly weighted.
    fastest_path = nx.dijkstra_path(G_coord, coord_origin, coord_destination)
    #Creation of the map associated to the route.
    map = StaticMap(750, 750)
    for i in range(len(fastest_path) - 1):
        coord1, coord2 = fastest_path[i], fastest_path[i + 1]
        line = Line([[coord1[1], coord1[0]], [coord2[1], coord2[0]]],
                    '#0000FFBB', 4)
        map.add_line(line)
        marker = CircleMarker([coord1[1], coord1[0]], 'red', 6)
        marker_outline = CircleMarker([coord1[1], coord1[0]], 'black', 8)
        map.add_marker(marker_outline)
        map.add_marker(marker)
    #Intentar coger el icono de internet y no tenerlo guardado como imagen local.
    dest_marker = IconMarker(
        [coord2[1], coord2[0]],
        '/home/victor/Documentos/AP2/Exercicis/Bicing/Icons/2344292-24.png',
        24, 24)
    map.add_marker(dest_marker)
    image = map.render()
    image.save(name_file)
Ejemplo n.º 4
0
def getmap(lat_server, lon_server, lat_client, lon_client, largeur, hauteur,
           zoom):
    m = StaticMap(largeur,
                  hauteur,
                  url_template='http://b.tile.osm.org/{z}/{x}/{y}.png')

    m.add_line(
        Line(((lon_server, lat_server), (lon_client, lat_client)), 'blue', 3))

    icon_flag_1 = IconMarker((lon_client, lat_client), 'icon/icon-flag.png',
                             12, 32)
    m.add_marker(icon_flag_1)
    icon_flag_2 = IconMarker((lon_server, lat_server), 'icon/icon-flag.png',
                             12, 32)
    m.add_marker(icon_flag_2)

    image = m.render()
    image.save('map/map.png')
Ejemplo n.º 5
0
def makemap(lat, lon, id):
    map = StaticMap(args.mapwidth,
                    args.mapheight,
                    80,
                    url_template='http://a.tile.osm.org/{z}/{x}/{y}.png')
    marker = IconMarker((lon, lat), 'utils/images/icon-flag.png', 12, 32)
    map.add_marker(marker)
    image = map.render(zoom=15)
    image.save('utils/images/geocoded/{}.png'.format(id))
    log.info("Generated and saved {}.png".format(id))
    return
def FindBusLocation(busName, routeCode):
    #routeCode = "2006"
    response = requests.post(
        "http://telematics.oasa.gr/api/?act=getBusLocation&p1={}".format(
            routeCode))
    json_response = response.json()
    #busCoordinateList = []
    stopCoordinateList = []
    #zoomValue = 14
    m = StaticMap(1200, 1200)
    if json_response:
        for resp in json_response:
            CS_LNG = float(resp["CS_LNG"])
            CS_LAT = float(resp["CS_LAT"])
            marker = IconMarker([CS_LNG, CS_LAT], "BusMarker.png", 17, 62)
            m.add_marker(marker)
            #busCoordinateList.append([CS_LNG,CS_LAT])

        #for coordinate in busCoordinateList:
        #marker = CircleMarker(coordinate, '#4286f4', 12)

        #zoomValue -= 1

    response = requests.post(
        "http://telematics.oasa.gr/api/?act=webGetStops&p1={}".format(
            routeCode))
    json_response = response.json()
    for resp in json_response:
        StopLng = float(resp["StopLng"])
        StopLat = float(resp["StopLat"])
        stopCoordinateList.append([StopLng, StopLat])

    #for coordinate in stopCoordinateList:
    #	marker = CircleMarker(coordinate, '#4286f4', 12)
    #	m.add_marker(marker)

    firstStop = CircleMarker(stopCoordinateList[0], '#37fc4b', 12)  #first stop
    lastStop = CircleMarker(stopCoordinateList[-1], '#f45c42', 12)  #last stop
    m.add_marker(firstStop)
    m.add_marker(lastStop)

    line = Line(
        stopCoordinateList, '#4286f4',
        4)  #draw a line through all stops, which is basically the route itself
    m.add_line(line)

    mapImg = m.render()
    mapImg.save("BusLocation.png")
    return mapImg
Ejemplo n.º 7
0
def process_icon(i, pnv):
    """Creates an IconMarker object with the properties from the request"""

    i_properties = dict(item.split(':') for item in i.split('|'))
    
    i_name = i_properties['name']
    i_offset_x = int(i_properties['offx'])
    i_offset_y = int(i_properties['offy'])

    i_lat = float(i_properties['coords'].split(',')[0])
    i_lon = float(i_properties['coords'].split(',')[1])

    pnv = pnv_counter(pnv)

    return IconMarker((i_lon, i_lat), './icons/{0}.png'.format(i_name), i_offset_x, i_offset_y), pnv
Ejemplo n.º 8
0
def create_map(coords, filename):
    image_width = 1200
    image_height = 630

    m = StaticMap(width=image_width,
                  height=image_height,
                  url_template="http://tile.stamen.com/toner/{z}/{x}/{y}.png")

    marker = IconMarker(coords, './location-marker.png', 18, 30)

    m.add_marker(marker)

    image = m.render()
    image.save(filename + '.png')
    return filename + '.png'
Ejemplo n.º 9
0
def global_data():
    """ fonction who search in the DB the distance reached by the the signal"""

    m = StaticMap(largeur,
                  hauteur,
                  url_template='http://b.tile.osm.org/{z}/{x}/{y}.png')
    cursor.execute("SELECT e_lat, e_long FROM coord")
    rows = cursor.fetchall()

    for row in rows:
        print row
        icon_flag = IconMarker((row[1], row[0]), 'icon/icon-flag.png', 12, 32)
        m.add_marker(icon_flag)

    global image
    image = m.render()
    image.save('map/GlobalMap.png')
    image = PhotoImage(file='map/GlobalMap.png')
    canvas.create_image(0, 0, image=image, anchor=NW)
Ejemplo n.º 10
0
 async def channel_forecast(self, ctx):
     channel = ReportChannel(ctx.bot, ctx.channel)
     base_map, cells = await channel.get_map()
     W = base_map.width
     H = base_map.height
     padding_y = base_map.padding[1]
     font_size = ceil(padding_y * 1.2)
     font = ImageFont.truetype(
         font=os.path.join(ctx.bot.bot_dir, "fonts", "Poppins-Regular.ttf"),
         size=font_size
     )
     markers = []
     for cell in cells:
         forecast = await cell.forecast(ctx.guild.id)
         if not forecast:
             continue
         coords = cell.center_coords
         coords = (coords.lng().degrees(), coords.lat().degrees())
         for hour in forecast:
             weather = Weather(ctx.bot, forecast[hour])
             icon_path = weather.icon_path
             m = {
                 'hour': hour,
                 'icon_path': icon_path,
                 'coords': coords
             }
             markers.append(m)
     max_hour = max([x['hour'] for x in markers], default=0)
     maps = []
     for i in range(max_hour+1):
         maps.append(deepcopy(base_map))
     for m in markers:
         hour = m['hour']
         frame = maps[hour]
         coords = m['coords']
         icon_path = m['icon_path']
         marker = IconMarker(coords, icon_path, 32, 32)
         frame.add_marker(marker)
     f = io.BytesIO()
     images = [m.render() for m in maps]
     zone = await ctx.tz()
     tz = timezone(zone)
     now_dt = datetime.now(tz=tz)
     initial_hr = now_dt.replace(minute=0)
     for i in range(len(images)):
         im = images[i]
         im = im.crop((0,0,W,(H-padding_y)))
         hour = initial_hr + timedelta(hours=i)
         timestr = hour.strftime('%I:%M %p')
         d = ImageDraw.Draw(im)
         w, h = d.textsize(timestr, font=font)
         x = (W - w) / 2
         d.text((x, ceil(H*.01)), timestr, font=font, fill=(0,0,0,255))
         images[i] = im
     imageio.mimwrite(f, images, format='GIF-PIL', duration=1, subrectangles=True)
     to_send = discord.File(io.BytesIO(f.getvalue()), filename='forecast.gif')
     p = ctx.prefix
     title = 'Pokémon Go Weather Forecast: Current Region'
     desc = f'You can help Meowth determine the correct pull times by using **{p}weather** to correct the predicted weather in raid channels!'
     embed = discord.Embed(title=title, description=desc)
     embed.set_image(url='attachment://forecast.gif')
     await ctx.send(embed=embed, file=to_send)
Ejemplo n.º 11
0
    async def metar(self, ctx: SlashContext, icao: str):

        global gustbool
        if len(icao) != 4:
            await ctx.send("ICAO code must be composed of 4 characters")
            return
        try:
            req = requests.get(
                'https://api.checkwx.com/metar/{}/decoded'.format(icao),
                headers=hdr,
                timeout=5)
        except Exception as err:
            await ctx.send(
                "Timeout error while requesting METAR, API servers are probably offline. Please try again later"
            )
            return print(err)

        print(f"Requested METAR for {icao.upper()}")

        if req.status_code != 200:
            print(
                f"Failed to retrieve METAR for {icao.upper()}, error {req.status_code}"
            )
            return await ctx.send(
                f"Error {req.status_code} while retrieving info for {icao.upper()}, either the website is down or the airport you chose is not available"
            )
        else:

            resp = req.json()

            if resp["results"] == 0:
                await ctx.send(
                    "No results, please check for typos or try a different ICAO"
                )
                return

            # with open('./Utils/wx.json', 'w') as f:
            #     json.dump(resp, f, indent=4)

            layerint = len(resp["data"][0]
                           ["clouds"])  # integer for number of cloud layers

            wxint = 0
            if "conditions" in resp["data"][0]:
                wxint = len(
                    resp["data"][0]["conditions"])  # presence of wx conditions

            visbool = "visibility" in resp["data"][0]  # presence of vis data

            if 'wind' in resp['data'][0]:
                gustbool = "gust_kts" in resp["data"][0][
                    "wind"]  # presence of gusts
                wind_bool = True
            else:
                wind_bool = False

            name = resp["data"][0]["station"]["name"]
            if wind_bool:
                degrees = resp["data"][0]["wind"]["degrees"]
                speed = resp["data"][0]["wind"]["speed_kts"]
            temp = resp["data"][0]["temperature"]["celsius"]
            dew = resp["data"][0]["dewpoint"]["celsius"]
            humidity = resp["data"][0]["humidity"]["percent"]
            inhg = resp["data"][0]["barometer"]["hg"]
            hpa = resp["data"][0]["barometer"]["hpa"]
            obs = resp["data"][0]["observed"]
            cond = resp["data"][0]["flight_category"]
            raw = resp["data"][0]["raw_text"]

            points = []

            lat: float = resp["data"][0]["station"]["geometry"]["coordinates"][
                1]
            long: float = resp["data"][0]["station"]["geometry"][
                "coordinates"][0]

            points.append(tuple([lat, long]))

            marker_outline = CircleMarker((long, lat), 'white', 18)
            marker = CircleMarker((long, lat), '#0036FF', 12)
            icon_flag = IconMarker((long + 0.008, lat),
                                   './Utils/icon-flag.png', 12, 32)

            m = StaticMap(700, 300, 10, 10)
            m.add_marker(marker_outline)
            m.add_marker(marker)
            m.add_marker(icon_flag)

            image = m.render(zoom=8)
            image.save('Utils/metar.png')
            file = discord.File('Utils/metar.png')

            metar = discord.Embed(title="Requested METAR for {} - {}".format(
                icao.upper(), name),
                                  description="Raw: {}".format(raw),
                                  colour=discord.Colour.from_rgb(97, 0, 215))
            if wind_bool:
                if not gustbool:
                    metar.add_field(name="Wind:",
                                    value="{}° at {} kts".format(
                                        degrees, speed))
                else:
                    gust = resp["data"][0]["wind"]["gust_kts"]
                    metar.add_field(name="Wind:",
                                    value="{}° at {} kts, gusts {} kts".format(
                                        degrees, speed, gust))
            else:
                metar.add_field(name="Wind:", value="Calm")

            metar.add_field(name="Temp/Dewpoint:",
                            value="{}°C/ {}°C".format(temp, dew))
            metar.add_field(name="Altimeter:",
                            value="{} hPa/ {} inHg".format(hpa, inhg))
            if visbool:
                vismil = resp["data"][0]["visibility"]["miles"]
                vismet = resp["data"][0]["visibility"]["meters"]
                metar.add_field(name="Visibility:",
                                value="{} meters/ {} miles".format(
                                    vismet, vismil))

            metar.add_field(name="Humidity:", value="{}%".format(humidity))
            metar.set_thumbnail(
                url=
                "https://cdn.discordapp.com/attachments/651086904925749252/802617703809548298/ezgif.com-gif-maker_3.gif"
            )
            metar.set_footer(
                text="Observed at {}. Flight category: {}".format(obs, cond))
            if wxint > 0:
                weather = resp["data"][0]["conditions"][0]["text"]
                metar.add_field(name="Weather condition:",
                                value="{}".format(weather))

            if layerint == 1:
                clouds = resp["data"][0]["clouds"][0]["text"]
                if 'feet' in resp["data"][0]["clouds"][0]:
                    clofeet = resp["data"][0]["clouds"][0]["feet"]
                    metar.add_field(name="Cloud condition:",
                                    value="{}ft {}".format(clofeet, clouds))
                else:
                    metar.add_field(name="Cloud condition:",
                                    value="{}".format(clouds))
            elif layerint == 2:
                clouds = resp["data"][0]["clouds"][0]["text"]
                clofeet = resp["data"][0]["clouds"][0]["feet"]
                clouds1 = resp["data"][0]["clouds"][1]["text"]
                clofeet1 = resp["data"][0]["clouds"][1]["feet"]
                metar.add_field(name="Cloud condition:",
                                value="{}ft {}/ {}ft {}".format(
                                    clofeet, clouds, clofeet1, clouds1))
            elif layerint == 3:
                clouds = resp["data"][0]["clouds"][0]["text"]
                clofeet = resp["data"][0]["clouds"][0]["feet"]
                clouds1 = resp["data"][0]["clouds"][1]["text"]
                clofeet1 = resp["data"][0]["clouds"][1]["feet"]
                clouds2 = resp["data"][0]["clouds"][2]["text"]
                clofeet2 = resp["data"][0]["clouds"][2]["feet"]
                metar.add_field(name="Cloud condition:",
                                value="{}ft {}/ {}ft {}/ {}ft {}".format(
                                    clofeet, clouds, clofeet1, clouds1,
                                    clofeet2, clouds2))
            else:
                metar.add_field(name="Cloud condition:",
                                value="Not Specified / Cloud data error")

            metar.set_image(url='attachment://metar.png')

            await ctx.send(embed=metar, file=file)