Example #1
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())
Example #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
Example #3
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)
Example #4
0
    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
Example #5
0
def render_single_tile(m: StaticMap, ext: list) -> Image:
    """
    Revised version of StaticMap.render() allows explicit extent + empty maps
    Args:
        m: Static map object for rendering
        ext: the map extent in  (min_lon, min_lat, max_lon, max_lat)

    Returns:
        The returned RGB image as an PIL.Image
    """
    ex_poly = [[ext[0], ext[1]],
               [ext[0], ext[3]],
               [ext[2], ext[1]],
               [ext[2], ext[3]]]
    polygon = Polygon(ex_poly, 'white', 'white', True)
    m.add_polygon(polygon)
    m.zoom = m._calculate_zoom()

    # get extent of all lines
    extent = ext

    # calculate center point of map
    lon_center, lat_center = (extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2
    m.x_center = _lon_to_x(lon_center, m.zoom)
    m.y_center = _lat_to_y(lat_center, m.zoom)

    image = Image.new('RGB', (m.width, m.height), m.background_color)

    m._draw_base_layer(image)
    m.polygons.remove(polygon)
    m._draw_features(image)
    return image
Example #6
0
    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
Example #7
0
 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")
Example #8
0
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
Example #9
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])
Example #10
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
Example #11
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)
Example #12
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')
Example #13
0
    def render_image(self):
        self.static_map = StaticMap(
            700, 700)  #, url_template='http://a.tile.osm.org/{z}/{x}/{y}.png')
        self.drone_marker = CircleMarker(self.map_coordinates, '#0036FF', 12)
        self.static_map.add_marker(self.drone_marker)
        for stationary_obstacle in self.stationary_obstacles:
            self.static_map.add_marker(stationary_obstacle)

        for moving_obstacle in self.moving_obstacles:
            self.static_map.add_marker(moving_obstacle)

        self.image = self.static_map.render(zoom=17)
        self.image.save('map.png')
def where(update, context):
    try:
        lat, lon = update.message.location.latitude, update.message.location.longitude
        fitxer = "%d.png" % random.randint(1000000, 9999999)
        mapa = StaticMap(500, 500)
        mapa.add_marker(CircleMarker((lon, lat), 'blue', 10))
        imatge = mapa.render()
        imatge.save(fitxer)
        context.bot.send_photo(chat_id=update.effective_chat.id,
                               photo=open(fitxer, 'rb'))
        os.remove(fitxer)
    except Exception as e:
        print(e)
        context.bot.send_message(chat_id=update.effective_chat.id, text='💣')
Example #15
0
 async def get_map(self):
     covering = await self.level_10_covering()
     cells = [S2_L10(self.bot, x) for x in covering]
     approx_width = sqrt(len(cells))
     px_dim = 100 * ceil(approx_width)
     lines = []
     for x in cells:
         lines.extend(x.get_border())
     url_template = 'https://a.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png'
     m = StaticMap(px_dim, ceil(px_dim * 1.2), 5, ceil(px_dim / 10),
                   url_template)
     for l in lines:
         m.add_line(l)
     return m, cells
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'
Example #17
0
def plotpop(g, dist, lat, lon):
    # crear mapa i setejar visibilitat
    mapa = StaticMap(500, 500)
    g = setVisibilityNodes(g, dist, lat, lon)

    # afegir markers
    mapa = paintNodes(g, mapa, True)

    # crear imatge
    try:
        img = mapa.render()
    except:
        raise MyExceptions.MapRenderException

    return img
Example #18
0
def print_path(path, G, file):
    m = StaticMap(800, 800)
    # go through the path and print every node
    for i in range(len(path) - 1):
        marker = CircleMarker(path[i], 'red', 6)
        m.add_marker(marker)
        coordinates = [path[i], path[i + 1]]
        line = Line(coordinates, 'blue', 1)
        m.add_line(line)
    marker = CircleMarker(path[len(path) - 1], 'red', 6)
    m.add_marker(marker)
    image = m.render()
    image.save(file)
Example #19
0
def dibujarPlotpop(distancia, lat, lon):
    myMap = StaticMap(600, 600)
    tam = 3
    listaC = listaCercanos(distancia, lat, lon)
    global matrizBloques
    for x in listaC:
        for y in matrizBloques[x[1]][x[0]]:
            latAux = grafo.node[y]['latitude']
            lonAux = grafo.node[y]['longitude']
            dist = calcularDistKm(lat, lon, latAux, lonAux)
            if dist < distancia:
                marker = CircleMarker(
                    (lonAux, latAux), 'red',
                    math.ceil(grafo.node[y]['population'] / (30000 * tam)) + 1)
                myMap.add_marker(marker)
    image = myMap.render()
    image.save('plotpop.png')
Example #20
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)
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
Example #22
0
    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
Example #23
0
def draw_map_route(graph, src, dst):
    fitxer = "%d.png" % random.randint(1000000, 9999999)
    route_node_list = graphs.get_graph_route(graph, src, dst)
    mapa = StaticMap(500, 500)
    mapa.add_marker(CircleMarker(route_node_list[0].lon_lat(), 'blue', 5))
    for i in range(len(route_node_list) - 1):
        mapa.add_marker(
            CircleMarker(route_node_list[i + 1].lon_lat(), 'blue', 5))
        mapa.add_line(
            Line((route_node_list[i].lon_lat(),
                  route_node_list[i + 1].lon_lat()), 'blue', 1))
    imatge = mapa.render()
    imatge.save(fitxer)
    return fitxer
Example #24
0
def plotgraph(G, name_file):
    map = StaticMap(750, 750)
    for station in G.edges:
        coord1, coord2 = station[0], station[1]
        line = Line([[coord1.lon, coord1.lat], [coord2.lon, coord2.lat]],
                    '#0000FFBB', 2)
        map.add_line(line)

    for station in G.nodes:
        marker = CircleMarker([station.lon, station.lat], 'red', 4)
        marker_outline = CircleMarker([station.lon, station.lat], 'black', 8)
        map.add_marker(marker_outline)
        map.add_marker(marker)
    image = map.render()
    image.save(name_file)
Example #25
0
def route_get_images(scenario):
    cea_config = current_app.cea_config
    project_path = cea_config.project
    locator = cea.inputlocator.InputLocator(
        os.path.join(project_path, scenario))
    zone_path = locator.get_zone_geometry()
    if not os.path.isfile(zone_path):
        abort(404, 'Zone file not found')
    cache_path = os.path.join(project_path, '.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)

        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)

    import base64
    with open(image_path, 'rb') as imgFile:
        image = base64.b64encode(imgFile.read())
    return image
Example #26
0
def render_map(map_: StaticMap,
               retry=True) -> t.Optional[Image.Image]:  # no test coverage
    try:
        img = map_.render()
    except Exception:
        if retry:
            return render_map(map_, retry=False)
        log.error("Error rendering map", exc_info=True)
        img = None
    return img
Example #27
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)
Example #28
0
class OsmStaticMapPlotter(Plotter):
    def __init__(self, width=2000, height=1500):
        Plotter.__init__(self)
        self.static_map_ = StaticMap(
            width,
            height,
            url_template="http://a.tile.osm.org/{z}/{x}/{y}.png")

    def DrawLine(self, src_gps, dst_gps, color, width):
        self.static_map_.add_line(
            Line(((src_gps[1], src_gps[0]), (dst_gps[1], dst_gps[0])), color,
                 width))

    def DrawPoint(self, node_gps, color, size):
        self.static_map_.add_marker(
            CircleMarker((node_gps[1], node_gps[0]), color, size))

    def SaveMap(self, map_filename):
        image = self.static_map_.render()
        image.save(map_filename)
Example #29
0
def drawRoute(G, path):
    m = StaticMap(400, 400)
    m.add_marker(
        CircleMarker(
            (G.nodes[path[0]]['longitude'], G.nodes[path[0]]['latitude']),
            'red', 3))
    for i in range(len(path) - 1):
        m.add_marker(
            CircleMarker((G.nodes[path[i + 1]]['longitude'],
                          G.nodes[path[i + 1]]['latitude']), 'red', 3))
        m.add_line(
            Line(
                ((G.nodes[path[i]]['longitude'], G.nodes[path[i]]['latitude']),
                 (G.nodes[path[i + 1]]['longitude'],
                  G.nodes[path[i + 1]]['latitude'])), 'blue', 1))
    image = m.render()
    image.save('plotroute.png')
Example #30
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]
Example #31
0
import csv
import random
from staticmap import StaticMap, CircleMarker

m = StaticMap(1000, 900, url_template='http://a.tile.stamen.com/toner/{z}/{x}/{y}.png')


with open('data/crimes-robbery.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    for row in reader:
        marker = CircleMarker((float(row[1]), float(row[0])), (232, 152, 16, 180), 6)
        m.add_marker(marker)

image = m.render(center=[-87.684871189, 41.8348221989])
image.save('robbery.png')
Example #32
0
from staticmap import StaticMap
from boundary import Boundary, Range, LatLon
import pickle
import pprint
import glob

from fileio import Fileio

x_range = Range(-87.69215,-87.634896)
y_range = Range(41.858952,41.886565)
boundary = Boundary(x_range, y_range)

center = boundary.center()
center_latlon = LatLon(lon=center[0], lat=center[1])

print StaticMap.latlon2xy_tile(center_latlon.lat, center_latlon.lon, 12)


print center_latlon
metainfo = StaticMap.get_map("chicago.png", \
    center={'lat':center_latlon.lat, 'lon':center_latlon.lon}, \
    zoom=14, scale=2, maptype="roadmap")

pprint.pprint(metainfo)

print StaticMap.xy2latlon(metainfo, 0, 0)
print StaticMap.latlon2xy_centered(metainfo, center_latlon.lat, center_latlon.lon)


ll = metainfo['bbox']['low_left']
ur = metainfo['bbox']['upper_right']
Example #33
0
 def testLat(self):
     for lat in range(-89, 89, 2):
         for zoom in range(0, 10):
             y = StaticMap._lat_to_y(lat, zoom)
             l = StaticMap._y_to_lat(y, zoom)
             self.assertAlmostEqual(lat, l, places=5)
Example #34
0
 def testLon(self):
     for lon in range(-180, 180, 20):
         for zoom in range(0, 10):
             x = StaticMap._lon_to_x(lon, zoom)
             l = StaticMap._x_to_lon(x, zoom)
             self.assertAlmostEqual(lon, l, places=5)
Example #35
0
    def update_geometry(self, configuration_code, force_update=False):
        """
        Update the geometry of a questionnaire based on the GeoJSON found in the
        data json.

        Args:
            configuration_code:

        Returns:
            -
        """
        def get_geometry_from_string(geometry_string):
            """
            Extract and convert the geometry from a (GeoJSON) string.

            Args:
                geometry_string: The geometry as (GeoJSON) string.

            Returns:
                A GeometryCollection or None.
            """

            if geometry_string is None:
                return None

            try:
                geometry_json = json.loads(geometry_string)
            except json.decoder.JSONDecodeError:
                return None
            geoms = []
            for feature in geometry_json.get('features', []):
                try:
                    feature_geom = GEOSGeometry(
                        json.dumps(feature.get('geometry')))
                except ValueError:
                    continue
                except GDALException:
                    continue
                geoms.append(feature_geom)

            if geoms:
                return GeometryCollection(tuple(geoms))

            else:
                return None

        geometry_value = self.configuration_object.get_questionnaire_geometry(self.data)
        geometry = get_geometry_from_string(geometry_value)

        geometry_changed = self.geom != geometry

        try:
            self.geom = geometry
            self.save()
        except ValidationError:
            return

        if self.geom is None or (not force_update and not geometry_changed):
            # If there is no geometry or if it did not change, there is no need
            # to create the static map image (again)
            return

        # Create static map
        width = 1000
        height = 800
        marker_diameter = 24
        marker_color = '#0036FF'

        m = StaticMap(width, height)

        for point in iter(self.geom):
            m.add_marker(CircleMarker((point.x,  point.y), marker_color, marker_diameter))

        bbox = None
        questionnaire_country = self.get_question_data('qg_location', 'country')

        if len(questionnaire_country) == 1:
            country_iso3 = questionnaire_country[0].replace('country_', '')
            country_iso2 = settings.CONFIGURATION_COUNTRY_ISO_MAPPING.get(
                country_iso3)

            if country_iso2:
                r = requests.get(
                    'http://api.geonames.org/countryInfoJSON?username=wocat_webdev&country={}'.format(
                        country_iso2))
                geonames_country = r.json().get('geonames')

                if len(geonames_country) == 1:
                    ctry = geonames_country[0]
                    poly_coords = [
                        [ctry.get('west'), ctry.get('north')],
                        [ctry.get('west'), ctry.get('south')],
                        [ctry.get('east'), ctry.get('south')],
                        [ctry.get('east'), ctry.get('north')],
                        [ctry.get('west'), ctry.get('north')]
                    ]

                    bbox = Polygon(poly_coords, None, None)

        if bbox:
            m.add_polygon(bbox)
            image = m.render()
        else:
            # No bbox found, guess zoom level
            image = m.render(zoom=6)

        map_folder = get_upload_folder_path(str(self.uuid), subfolder='maps')
        if not os.path.exists(map_folder):
            os.makedirs(map_folder)

        filename = '{}_{}.jpg'.format(self.uuid, self.version)
        image.save(os.path.join(map_folder, filename))
Example #36
0
             'height':600, \
             'filename': 'new_york.png', \
             'markers': [{'lat': 40.714728, 'lon':-73.998672, 'filename': 'accident.png', 'offset_x': -16, 'offset_y': 0}], \
             'paths': ( ({'lat': 40.714728, 'lon': -73.998672}, {'lat': 40.714728, 'lon': -73.80234}) ) \
             },\
         {   'lat': 27.790491, \
             'lon':-81.584473, \
             'zoom':7, \
             'width':600, \
             'height':600, \
             'filename': 'florida.png', \
             'markers': [{'lat': 27.790491, 'lon':-81.584473, 'filename': 'accident.png', 'offset_x': 0, 'offset_y': 0}],
             'paths': () \
             }]
         
 output_dir = 'tests'
 
 my_map = StaticMap()
 for test_map in maps:
     print "Generating... " + test_map['filename']
     my_map.setup_map(lat = test_map['lat'], lon = test_map['lon'], zoom = test_map['zoom'], map_width = test_map['width'], map_height =  test_map['height'])
     
     for path in test_map['paths']:
         my_map.add_path({'lat': 40.714728, 'lon': -73.998672}, {'lat': 40.924728, 'lon': -73.98234})
         
     for marker in test_map['markers']:
         my_map.add_marker(marker)
         
     my_map.save_map(output_dir + '/' + test_map['filename'])
     print "Generated"
     my_map.reset()
Example #37
0
import csv
import random
from staticmap import StaticMap, CircleMarker

m = StaticMap(1000, 900, url_template='http://a.tile.stamen.com/toner/{z}/{x}/{y}.png')

def label_to_color(label):
    alpha = 180
    return {
        'good': (0,153,102,alpha),
        'moderate': (255,222,51,alpha),
        'unhealthy for sensitive': (255,153,51,alpha),
        'unhealthy': (204,0,51,alpha),
        'very unhealthy': (102,0,153,alpha),
        'hazardous': (126,0,35,alpha)
    }[label]

with open('data/airVis.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    for row in reader:
        marker = CircleMarker((float(row[1]), float(row[0])), label_to_color(row[2]), 6)
        m.add_marker(marker)

image = m.render(zoom=6, center=[15.2793976568, 50.5197351804])
image.save('marker-k3-minkowski.png')

random.random