예제 #1
0
def plot_mpe_prediction(edge_index_to_tuples, node_locations, mpe_result,
                        used_edges, total_route, src_node, dst_node, map_name):
    m = StaticMap(2000,
                  1500,
                  url_template="http://a.tile.osm.org/{z}/{x}/{y}.png")
    for used_edge in used_edges:
        src_gps = node_locations[edge_index_to_tuples[used_edge][0]]
        dst_gps = node_locations[edge_index_to_tuples[used_edge][1]]
        m.add_line(
            Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])), "black",
                 5))
    src_gps = node_locations[src_node]
    dst_gps = node_locations[dst_node]
    m.add_marker(CircleMarker((src_gps[1], src_gps[0]), "blue", 8))
    m.add_marker(CircleMarker((dst_gps[1], dst_gps[0]), "blue", 8))
    for used_edge in total_route:
        if used_edge not in used_edges:
            src_gps = node_locations[edge_index_to_tuples[used_edge][0]]
            dst_gps = node_locations[edge_index_to_tuples[used_edge][1]]
            m.add_line(
                Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])),
                     "green", 10))
    for active_variable_index in mpe_result:
        if active_variable_index in edge_index_to_tuples and active_variable_index not in used_edges:
            edge_tuple = edge_index_to_tuples[active_variable_index]
            src_gps = node_locations[edge_tuple[0]]
            dst_gps = node_locations[edge_tuple[1]]
            m.add_line(
                Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])),
                     "red", 5))
    image = m.render()
    image.save(map_name)
예제 #2
0
def plot_mar_prediction(edge_index_to_tuples, node_locations, marginals,
                        correct_next, used_edges, src_node, dst_node,
                        map_name):
    m = StaticMap(2000,
                  1500,
                  url_template="http://a.tile.osm.org/{z}/{x}/{y}.png")
    for key in marginals:
        if key in edge_index_to_tuples:
            cur_marginal = marginals[key]
            edge_tuple = edge_index_to_tuples[key]
            density = math.exp(cur_marginal[1])
            src_gps = node_locations[edge_tuple[0]]
            dst_gps = node_locations[edge_tuple[1]]
            m.add_line(
                Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])),
                     get_color(density), 5))
    for used_edge in used_edges:
        src_gps = node_locations[edge_index_to_tuples[used_edge][0]]
        dst_gps = node_locations[edge_index_to_tuples[used_edge][1]]
        m.add_line(
            Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])), "black",
                 5))
    src_gps = node_locations[src_node]
    dst_gps = node_locations[dst_node]
    m.add_marker(CircleMarker((src_gps[1], src_gps[0]), "blue", 3))
    m.add_marker(CircleMarker((dst_gps[1], dst_gps[0]), "blue", 3))
    src_gps = node_locations[edge_index_to_tuples[correct_next][0]]
    dst_gps = node_locations[edge_index_to_tuples[correct_next][1]]
    m.add_line(
        Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])), "green", 2))
    image = m.render()
    image.save(map_name)
예제 #3
0
def main():
    sm = StaticMap()
    im = Image.open(urlopen(sm.get()))
    im = im.convert('RGB')
    w, h = im.size[0], im.size[1] - 22  # remove Google footer
    im = im.crop([0, 0, w, h])
    arr = asarray(im)
    char_array = [['' for i in range(w)] for j in range(h)]
    found_start = False
    known_markers = [(31, 60, 19), (44, 35, 17), (0, 0, 0)]
    for i in range(w):
        for j in range(h):
            _col = tuple(arr[j, i])
            _char = col_to_char(_col)
            if _col[0] < 60 and _col[1] < 60 and _col[2] < 60:
                print("Mark found!")
                if found_start:
                    _char = 'B'
                else:
                    _char = 'A'
                    found_start = True
            char_array[j][i] = _char

    with open(sm.name(), 'wb') as cmap:
        for line in char_array:
            for c in line:
                cmap.write(c.encode())
            cmap.write('\r\n'.encode())
예제 #4
0
파일: graph.py 프로젝트: rogerrm/graphbot
    def plotgraph(self, lat, lon, dist):
        '''
        Returns the plot of the graph of the edges between cities that
        have distance than dist from (lat, lon)
        '''
        mapa = StaticMap(400, 400)
        some = False

        for edge in self.G.edges:
            if self.is_plottable(edge, (lat, lon), dist):
                some = True
                # Staticmap needs coordinates in order (Longitude, Latitude)
                rev_coords_0 = tuple(reversed(self.coordinates[edge[0]]))
                rev_coords_1 = tuple(reversed(self.coordinates[edge[1]]))
                mapa.add_line(Line((rev_coords_0, rev_coords_1), 'blue', 3))

        if not some:
            return

        image = mapa.render()
        bio = BytesIO()
        bio.name = 'map.png'
        image.save(bio)
        bio.seek(0)
        return bio
예제 #5
0
def draw_map(point1, point2):
  url_template = "https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png"
  #url_template = "http://a.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png" # alternatiba_1
  #url_template = "http://tile.memomaps.de/tilegen/{z}/{x}/{y}.png" # alternatiba_2
  
  map_width = 600
  map_height = 400
  z = 8
  fName = str(uuid.uuid4().hex)

  m = StaticMap(map_width, map_height, url_template=url_template)

  coords1 = point_to_coordinates(point1)
  coords2 = point_to_coordinates(point2)

  marker_outline1 = CircleMarker(coords1, 'white', 18)
  marker1 = CircleMarker(coords1, '#0036FF', 12)
  m.add_marker(marker_outline1)
  m.add_marker(marker1)

  marker_outline2 = CircleMarker(coords2, 'white', 18)
  marker2 = CircleMarker(coords2, '#0036FF', 12)
  m.add_marker(marker_outline2)
  m.add_marker(marker2)

  image = m.render(zoom=z)
  image.save("./maps/" + fName + ".png")

  return fName+".png"
예제 #6
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
예제 #7
0
    def find_drone_path(self):  # desired path of drone
        m = StaticMap(1200, 950)

        marker_outline = CircleMarker(self.start, 'white', 18)
        marker = CircleMarker(self.start, '#0036FF', 12)

        m.add_marker(marker_outline)
        m.add_marker(marker)

        for t in self.targets:
            target_marker_outline = CircleMarker(t, 'white', 18)
            target_marker = CircleMarker(t, 'red', 12)

            m.add_marker(target_marker_outline)
            m.add_marker(target_marker)

        path = []
        path.append(self.start)
        for t in self.targets:
            path.append(t)

        m.add_line(Line(path, 'blue', 3))

        image = m.render(zoom=self.zoom)
        image.save(r'GMap\drone_path.png')
예제 #8
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)
예제 #9
0
def dijkstra_route(G, position):
    m = StaticMap(400, 500)

    last = int(-1)
    time = int(0)

    path = nx.dijkstra_path(G, -1, 0)

    # We go through each node in the minimum path between the start and end.
    for i in path:

        if (i != -1):
            coord1 = swap(position[last])
            coord2 = swap(position[i])
            e = (last, i)
            time += G.get_edge_data(*e)['weight']

            if i == path[1] or i == 0:
                # Walking -> green edge (first or last edge).
                m.add_line(Line((coord1, coord2), 'green', 2))

            else:
                # Riding a Bicycle -> blue edge.
                m.add_line(Line((coord1, coord2), 'blue', 2))

        # Origin and destination points are purple and bigger.
        if (i > 0):
            m.add_marker(CircleMarker(swap(position[i]), 'red', 2))
        else:
            m.add_marker(CircleMarker(swap(position[i]), 'purple', 4))
        last = i

    return m, int(time)
예제 #10
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])
예제 #11
0
def draw_map():
    m = StaticMap(4000, 4000)
    for key, access_point in access_point_data.items():
        if not ('lat' in access_point and 'lng' in access_point):
            continue
        coords = (access_point['lat'], access_point['lng'])
        if access_point['lng'] - -34.611944444444 > 0.1:
            continue
        if access_point['lat'] - -58.364722222222 > 0.1:
            continue

        colors = {
            'open': 'red',
            'wep': 'red',
            'wpa': 'yellow',
            'wpa2': 'green'
        }
        marker_outline = CircleMarker(coords,
                                      colors[access_point['encryption']], 18)
        marker = CircleMarker(coords, colors[access_point['encryption']], 12)

        m.add_marker(marker_outline)
        m.add_marker(marker)

    image = m.render(zoom=15)
    temp_file = NamedTemporaryFile(suffix='.png')
    image.save(temp_file.name)
    image.save('/home/lcubo/test1.png')
    return temp_file
예제 #12
0
파일: graph.py 프로젝트: rogerrm/graphbot
    def route(self, src, dst):
        '''
        Returns the plot of the shortest route between src and dst
        '''
        real_src = self.get_most_similar(src)
        real_dst = self.get_most_similar(dst)

        if real_src and real_dst:
            try:
                path = nx.algorithms.shortest_paths.generic.shortest_path(
                    self.G, source=real_src, target=real_dst, weight='weight')
            except Exception as e:
                return c.PATH_FAIL

            mapa = StaticMap(400, 400)
            for cities in zip([''] + path, path):
                rev_coords_1 = tuple(reversed(self.coordinates[cities[1]]))
                circle = CircleMarker(rev_coords_1, 'red', 4)
                mapa.add_marker(circle)
                if '' in cities:
                    continue
                rev_coords_0 = tuple(reversed(self.coordinates[cities[0]]))
                mapa.add_line(Line((rev_coords_0, rev_coords_1), 'blue', 3))

            image = mapa.render()
            bio = BytesIO()
            bio.name = 'map.png'
            image.save(bio)
            bio.seek(0)
            return bio

        if not real_src:
            return c.SOURCE_FAIL

        return c.DEST_FAIL
예제 #13
0
파일: graph.py 프로젝트: rogerrm/graphbot
    def plotpop(self, lat, lon, dist):
        '''
        Returns the plot of the graph of the cities that have distance
        lower than dist from (lat, lon)
        '''
        mapa = StaticMap(400, 400)
        some = False

        max_pop = 0
        for node in self.G.nodes:
            if self.is_plottable((node, node), (lat, lon), dist):
                some = True
                if max_pop < self.populations[node]:
                    max_pop = self.populations[node]

        if not some:
            return

        for node in self.G.nodes:
            if self.is_plottable((node, node), (lat, lon), dist):
                rev_coords = tuple(reversed(self.coordinates[node]))
                circle = CircleMarker(
                    rev_coords, 'red',
                    self.populations[node] * c.CIRCLE_SCALE / max_pop)
                mapa.add_marker(circle)

        image = mapa.render()
        bio = BytesIO()
        bio.name = 'map.png'
        image.save(bio)
        bio.seek(0)
        return bio
예제 #14
0
def main(
    conn: connection,
    journey_id: int,
    last_location: t.Optional[dict],
    current_lat: float,
    current_lon: float,
    current_distance: float,
    steps_data: list[dict],
    gargling_info: dict[int, dict],
) -> t.Optional[bytes]:
    old_coords, locations, overview_coords, detailed_coords = traversal_data(
        conn,
        journey_id,
        last_location,
        current_lat,
        current_lon,
        current_distance,
        steps_data,
    )
    template = "https://a.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png"
    height = 600
    width = 1000
    overview_map = StaticMap(width=width, height=height, url_template=template)
    if old_coords:
        overview_map.add_line(Line(old_coords, "grey", 2))
    for lon, lat in locations:
        overview_map.add_marker(CircleMarker((lon, lat), "blue", 6))
    overview_map.add_line(Line(overview_coords, "red", 2))
    overview_map.add_marker(CircleMarker((current_lon, current_lat), "red", 6))

    detailed_map = StaticMap(width=width, height=height, url_template=template)
    start = detailed_coords[0]["coords"][0]
    detailed_map.add_marker(CircleMarker(start, "black", 6))
    detailed_map.add_marker(CircleMarker(start, "grey", 4))
    for gargling in detailed_coords:
        color = gargling_info[gargling["gargling_id"]]["color_hex"]
        detailed_map.add_line(Line(gargling["coords"], "grey", 4))
        detailed_map.add_line(Line(gargling["coords"], color, 2))
        detailed_map.add_marker(
            CircleMarker(gargling["coords"][-1], "black", 6))
        detailed_map.add_marker(CircleMarker(gargling["coords"][-1], color, 4))
    legend = map_legend(detailed_coords, gargling_info)

    overview_img = render_map(overview_map)
    detailed_img = render_map(detailed_map)
    img = merge_maps(overview_img, detailed_img, legend)
    return img
예제 #15
0
def create_staticmaps(trail_id, base_uri):
    from .models import Trail
    current_trail = Trail.objects.get(pk=trail_id)

    try:
        static_thumbnail = StaticMap(425, 225, 10, 10, base_uri + '/trail/api/tile/{z}/{x}/{y}.png', tile_request_timeout=180)
        static_hero = StaticMap(1280, 480, 10, 10, base_uri + '/trail/api/tile/{z}/{x}/{y}.png', tile_request_timeout=180)

        for track in current_trail.tracks:
            coordinates = get_coordinates(track['points'])
            static_thumbnail.add_line(Line(coordinates, 'white', 11))
            static_hero.add_line(Line(coordinates, 'white', 11))

        for track in current_trail.tracks:
            coordinates = get_coordinates(track['points'])
            static_thumbnail.add_line(Line(coordinates, '#2E73B8', 5))
            static_hero.add_line(Line(coordinates, '#2E73B8', 5))

        image_thumbnail = static_thumbnail.render()
        image_hero = static_hero.render()

        file_thumbnail = io.BytesIO(b'')
        file_hero = io.BytesIO(b'')

        image_thumbnail.save(file_thumbnail, format='JPEG', optimize=True, progressive=True)
        image_hero.save(file_hero, format='JPEG', optimize=True, progressive=True)

        current_trail.thumbnail.delete(save=False)
        current_trail.thumbnail.save('thumbnail.jpg', file_thumbnail)

        current_trail.hero.delete(save=False)
        current_trail.hero.save('hero.jpg', file_hero)
    except:
        # TODO
        pass

    current_trail.is_draft = False
    current_trail.save()

    # TODO Translate
    to = mail(
        current_trail.name,
        'Your trail is ready.\n\n' +
        'https://mountainbikers.club' +
        reverse('trail__main', args=[current_trail.id])
    )
    to([current_trail.author.email])
예제 #16
0
 def setUpClass(cls) -> None:
     cls.m = StaticMap(IMG_WIDTH,
                       IMG_HEIGHT,
                       url_template=tile_server_dns_noport.replace(
                           '{p}', str(tile_server_ports[0])))
     cls.center = [36.1070, 36.7855]
     cls.s = generate_static_maps(tile_server_dns_noport, tile_server_ports)
     cls.ext = build_tile_extent(cls.center, radius_in_meters=50)
예제 #17
0
파일: prova.py 프로젝트: PolRenau14/LP
 def paintMapPop(self):
   m = StaticMap(2000,1500,20)
   for n in self.subgraph.nodes:
     point = (float(self.lista[int(n)][6]),float(self.lista[int(n)][5]))
     pob = float(self.lista[int(n)][4])
     tam = int(pob/100000)+1
     m.add_marker(CircleMarker(point,'red',tam))
   image = m.render()
   image.save("pop.png")
예제 #18
0
파일: maps.py 프로젝트: Ferja/GraphBot
def draw_map_plotpop(graph, dist, lat, lon):
    fitxer = "%d.png" % random.randint(1000000, 9999999)
    reduced_graph = graphs.get_graph_dist_lat_lon(graph, dist, lat, lon)
    mapa = StaticMap(500, 500)
    for node in reduced_graph:
        mapa.add_marker(
            CircleMarker(node.lon_lat(), 'blue', node.population / 1000000))
    imatge = mapa.render()
    imatge.save(fitxer)
    return fitxer
예제 #19
0
파일: geo.py 프로젝트: Ceshun/Poracle
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
예제 #20
0
    def display_start_map(self):  # Not Using
        m = StaticMap(1200, 950)

        marker_outline = CircleMarker(self.start, 'white', 18)
        marker = CircleMarker(self.start, '#0036FF', 12)

        m.add_marker(marker_outline)
        m.add_marker(marker)

        image = m.render(zoom=self.zoom)
        image.save(r'GMap\start_map.png')
예제 #21
0
파일: maps.py 프로젝트: Ferja/GraphBot
def draw_map_plotgraph(graph, dist, lat, lon):
    fitxer = "%d.png" % random.randint(1000000, 9999999)
    reduced_graph = graphs.get_graph_dist_lat_lon(graph, dist, lat, lon)
    mapa = StaticMap(500, 500)
    for node in reduced_graph:
        mapa.add_marker(CircleMarker(node.lon_lat(), 'blue', 5))
    for (u, v) in reduced_graph.edges():
        mapa.add_line(Line((u.lon_lat(), v.lon_lat()), 'blue', 1))
    imatge = mapa.render()
    imatge.save(fitxer)
    return fitxer
예제 #22
0
파일: prova.py 프로젝트: PolRenau14/LP
 def paintMapGraph(self):
   m = StaticMap(2000,1500,20)
   for (n, nbrs) in self.subgraph.edges:
     origen = (float(self.lista[int(n)][6]),float(self.lista[int(n)][5]))
     desti = (float(self.lista[int(nbrs)][6]),float(self.lista[int(nbrs)][5]))
     m.add_line(Line([origen,desti],'blue',2))
   for n in self.subgraph.nodes:
     point = (float(self.lista[int(n)][6]),float(self.lista[int(n)][5]))
     m.add_marker(CircleMarker(point,'red',7))
   image = m.render()
   image.save('graph.png')
예제 #23
0
    def get(self, scenario):
        project = request.args.get('project')
        if project is None:
            config = current_app.cea_config
        else:
            if not os.path.exists(project):
                abort(400, 'Project path: "{project}" does not exist'.format(project=project))
            config = cea.config.Configuration()
            config.project = project

        choices = list_scenario_names_for_project(config)
        if scenario in choices:
            locator = cea.inputlocator.InputLocator(os.path.join(config.project, scenario))
            zone_path = locator.get_zone_geometry()
            if os.path.isfile(zone_path):
                cache_path = os.path.join(config.project, '.cache')
                image_path = os.path.join(cache_path, scenario + '.png')

                zone_modified = os.path.getmtime(zone_path)
                if not os.path.isfile(image_path):
                    image_modified = 0
                else:
                    image_modified = os.path.getmtime(image_path)

                if zone_modified > image_modified:
                    # Make sure .cache folder exists
                    if not os.path.exists(cache_path):
                        os.makedirs(cache_path)

                    try:
                        zone_df = geopandas.read_file(zone_path)
                        zone_df = zone_df.to_crs(get_geographic_coordinate_system())
                        polygons = zone_df['geometry']

                        polygons = [list(polygons.geometry.exterior[row_id].coords) for row_id in range(polygons.shape[0])]

                        m = StaticMap(256, 160)
                        for polygon in polygons:
                            out = Polygon(polygon, 'blue', 'black', False)
                            m.add_polygon(out)

                        image = m.render()
                        image.save(image_path)
                    except Exception as e:
                        abort(400, str(e))

                import base64
                with open(image_path, 'rb') as imgFile:
                    image = base64.b64encode(imgFile.read())

                return {'image': image.decode("utf-8")}
            abort(400, 'Zone file not found')
        else:
            abort(400, 'Scenario does not exist', choices=choices)
예제 #24
0
def getmap(latitude, longitude, largeur, hauteur, zoom):
	m = StaticMap(largeur,hauteur, url_template='http://a.tile.osm.org/{z}/{x}/{y}.png')

	marker_outline = CircleMarker((longitude,latitude), 'white', 18)
	marker = CircleMarker((longitude,latitude), '#0036FF', 12)

	m.add_marker(marker_outline)
	m.add_marker(marker)

	image = m.render(zoom)
	image.save('marker.png')
예제 #25
0
def render_map():
    m = StaticMap(400,
                  400,
                  url_template='http://a.tile.osm.org/{z}/{x}/{y}.png')

    marker_outline = CircleMarker((42.883333, -9.883333), 'white', 18)
    marker = CircleMarker((42.883333, -9.883333), '#0036FF', 12)

    m.add_marker(marker_outline)
    m.add_marker(marker)
    image = m.render()
    image.save('map.png')
예제 #26
0
def drawPop(dist, lat, lon, graph):
    m = StaticMap(400, 400)
    returned = nodesAtDistFrom(dist, lat, lon, graph)
    G = returned[0]
    maxPop = returned[1]
    for node in list(G.nodes):
        m.add_marker(
            CircleMarker(
                (G.nodes[node]['longitude'], G.nodes[node]['latitude']), 'red',
                max(3, G.nodes[node]['pop'] * 15 / maxPop)))
    image = m.render()
    image.save('plotpop.png')
예제 #27
0
def generate_static_maps(url_port_template: str, ports: List[int]) -> List[StaticMap]:
    """
    Small utility function for generating multiple StaticMaps
    Args:
        url_port_template: The url_template but with an additional parameter {p} for the port
        ports: List of port numbers for the StaticMap objects

    Returns:
        List of StaticMaps object initialized with the correct url_templates
    """
    return [StaticMap(im_width, im_height, url_template=url_port_template.format(p=p, z='{z}', x='{x}', y='{y}'))
            for p in ports]
예제 #28
0
def location(bot, update):
    # Colors: Red, Blue, Purple, Green, Yellow, Brown, Orange, Grey   
    listOfColor = ['#8B0000', '#0000FF', '#8A2BE2', '#228B22', '#FFD700', '#8B4513', '#D2691E', '#808080'
    user = User.objects.get(chat_id=update.message.chat_id)
    point = Point(user.lon, user.lat)
    # Distance in KM to search the parkings close by
    radius = 0.5
    radius = radius / 40000 * 360
    circle = point.buffer(radius)
    shape = multiPolygonHandler.getMultiPolygonByPoint(point)
    m = StaticMap(600, 800, 12, 12, tile_size=256)
    marker_outline = CircleMarker((user.lon, user.lat), 'white', 22)
    marker = CircleMarker((user.lon, user.lat), 'Red', 18)
    m.add_marker(marker_outline)
    m.add_marker(marker)
    circleLine = Line(circle[0], color='red', width=3)
    geoCircle = GEOPolygon(circle[0])
    # Draw the circle for compare it with closest parkings
    m.add_line(circleLine)
    listPolygon, listOfColor2, listOfMultiPolygon = getAllPolygonsInCircleArea(geoCircle)
    i = 0
    if len(listPolygon) is not 0:
        for p in listPolygon:
            polygonLine = Line(p[0], color=listOfColor[i], width=3)
            m.add_line(polygonLine)
            i = i + 1
        image = m.render(zoom=14)
        fileName = 'ParkingStreet' + str(update.message.chat_id) + '.png'
        image.save(fileName)
        baseDir = settings.BASE_DIR
        picture = open(baseDir + '/' + fileName, 'rb')
        text = buildParkingZoneMessage(listOfMultiPolygon)
        btn_keyboard1 = KeyboardButton(text="Find another parking")
        btn_keyboard2 = KeyboardButton(text="Find closest electric charge point")
        btn_keyboard3 = KeyboardButton(text="Show my profile")
        btn_keyboard4 = KeyboardButton(text="That's all, thanks")
        custom_keyboard = [[btn_keyboard1], [btn_keyboard2], [btn_keyboard3], [btn_keyboard4]]
        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
        bot.sendPhoto(chat_id=update.message.chat_id, photo=picture)
        bot.sendMessage(chat_id=update.message.chat_id, text=text, parse_mode='HTML')
        bot.sendMessage(chat_id=update.message.chat_id, text='What do you want to do now?', reply_markup=reply_markup)
        userHandler.setUserBotActived(update.message.chat_id, True)
    else:
        btn_keyboard1 = KeyboardButton(text="Find another parking")
        btn_keyboard2 = KeyboardButton(text="Find closest electric charge point")
        btn_keyboard3 = KeyboardButton(text="Show my profile")
        btn_keyboard4 = KeyboardButton(text="That's all, thanks")
        custom_keyboard = [[btn_keyboard1], [btn_keyboard2], [btn_keyboard3], [btn_keyboard4]]
        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
        bot.sendMessage(chat_id=update.message.chat_id, text='There is no parking info close to your position.')
        bot.sendMessage(chat_id=update.message.chat_id, text='What do you want to do now?', reply_markup=reply_markup)
        userHandler.setUserBotActived(update.message.chat_id, True)
예제 #29
0
def generate_static_maps(url_port_template: str, ports: List[int]) -> List[StaticMap]:
    """
    Small utility function for generating multiple StaticMaps
    Args:
        url_port_template: The url_template but with an additional parameter {p} for the port
        ports: List of port numbers for the StaticMap objects

    Returns:
        List of StaticMaps object initialized with the correct url_templates
    """
    return [StaticMap(IMG_WIDTH, IMG_HEIGHT, url_template=url_port_template.replace('{p}', str(p)),
                      delay_between_retries=15, tile_request_timeout=5)
            for p in ports]
예제 #30
0
def ploting(G, position):
    m = StaticMap(400, 500)

    for j in G.edges():
        coord1 = swap(position[j[0]])
        coord2 = swap(position[j[1]])

        m.add_line(Line((coord1, coord2), 'blue', 1))

    for i in G.nodes():
        m.add_marker(CircleMarker(swap(position[i]), 'red', 2))

    return m