def gen_map(self):
        # read database
        connection = sqlite3.connect("posts.db")
        cursor = connection.cursor()
        sql = f"""SELECT * FROM "{self.handle}" """
        cursor.execute(sql)
        result = cursor.fetchall()
        connection.close()

        # Generate map, cluster class and create empty coordinates list
        if self.handle == "4x4theboiz":
            my_map = Map(location=[-25.25, 21.2], zoom_start=5)
        elif self.handle == "teampolarsteps":
            my_map = Map(location=[52.35, 5.3], zoom_start=9)
        elif self.handle == "cityofcapetown":
            my_map = Map(location=[-34.1, 18.420], zoom_start=10)
        elif self.handle == "backpackingtours":
            my_map = Map(location=[10, 100], zoom_start=3)
        elif self.handle == "tony_ontheroad":
            my_map = Map(location=[38.5, -2.75], zoom_start=6)
        elif self.handle == "rolling_sloane":
            my_map = Map(location=[55, 2.64], zoom_start=4)
        elif self.handle == "cape_secrets":
            my_map = Map(location=[-33.4, 18.8], zoom_start=8)

        else:
            my_map = Map(location=[0, 0], zoom_start=2)
        mc = MarkerCluster()
        coords = []

        # For each location convert address to coordinates, create popup and marker,
        # add to marker cluster
        for i in range(0, len(result), 1):

            popup_content = f"{result[i][0]} <br> " \
                            f"<a href={result[i][1]} > See Post"
            p = Popup(popup_content, max_width=400)
            mk = Marker([result[i][2], result[i][3]], p)
            mc.add_child(mk)
            lat_lon = (result[i][2], result[i][3])
            coords.append(lat_lon)

        # Add Polyline with coords
        if self.handle == "4x4theboiz":
            polyline = PolyLine(coords, color="red", weight=2, opacity=0.7)
            polyline.add_to(my_map)
        else:
            pass
        # Add Marker Cluster with mc
        my_map.add_child(mc)
        # Save the Map Instance Into a HTML file
        map_name = f"templates/map_{self.handle}.html"
        my_map.save(map_name)
Beispiel #2
0
def bicycling(origin, destination, alternative="bicycling"):
    """
    Recoge las cordenadas y dibuja el mapa con direcciones
    (en bici)
    """

    coordenadas = waypoints(origin=origin,
                            destination=destination,
                            alternative="bicycling")
    stopsdest = db.bicimad.find({
        "coordinates": {
            "$geoWithin": {
                "$centerSphere":
                [[coordenadas[2]["lng"], coordenadas[2]["lat"]],
                 0.00007885743614075527]
            }
        }
    }).limit(1)
    stopsorig = db.bicimad.find({
        "coordinates": {
            "$geoWithin": {
                "$centerSphere":
                [[coordenadas[1]["lng"], coordenadas[1]["lat"]],
                 0.00007885743614075527]
            }
        }
    }).limit(1)
    wpsneardest = []
    wpsnearorig = []
    for i in stopsdest:
        wpsneardest.append(i)
    for i in stopsorig:
        wpsnearorig.append(i)
    wpsneardest = wpsneardest[0]["coordinates"]
    wpsnearorig = wpsnearorig[0]["coordinates"]
    mapa = Map(location=[coordenadas[2]["lat"], coordenadas[2]["lng"]],
               zoom_start=14)
    chincheta2 = Marker(
        location=[coordenadas[1]["lat"], coordenadas[1]["lng"]],
        tooltip="origen",
        popup="o")
    chinchetad = Marker(
        location=[coordenadas[2]["lat"], coordenadas[2]["lng"]],
        tooltip="destino",
        popup="d")
    bicimador = Marker(location=[wpsnearorig[1], wpsnearorig[0]],
                       tooltip="orbici",
                       popup="bo",
                       icon=Icon(icon='heart', color='#f7b5f5'))
    bicimaddest = Marker(location=[wpsneardest[1], wpsneardest[0]],
                         tooltip="destbici",
                         popup="bd",
                         icon=Icon(icon="heart", color="#f7b5f5"))
    chincheta2.add_to(mapa)
    chinchetad.add_to(mapa)
    bicimador.add_to(mapa)
    bicimaddest.add_to(mapa)
    PolyLine(coordenadas[3], color="red", weight=2.5, opacity=1).add_to(mapa)
    return mapa
Beispiel #3
0
def plot_shape(folium_map: FoliumMap, shape_id: int, shape_popup: str, shape_color: str):
    """
    Plot the shape of ``shape_id`` onto ``folium_map``.

    ``shape_color`` can be any strings that represents color in CSS.
    """
    shape_coords = ctrl_shapes.get_shape_coords_by_id(shape_id)
    PolyLine(shape_coords, color=shape_color, popup=shape_popup).add_to(folium_map)
Beispiel #4
0
 def routeBuild(self):
     map = Map(self.coordList[0], zoom_start=9)
     popup_str = "Широта:{0:3f} Долгота:{1:3f}"
     lat1, lon1 = self.coordList[0]
     lat2, lon2 = self.coordList[len(self.coordList) - 1]
     PolyLine(self.coordList, color="red", weight=3, opacity=1).add_to(map)
     Marker([lat1, lon1],
            popup=popup_str.format(lat1, lon1),
            icon=Icon(color="blue")).add_to(map)
     Marker([lat2, lon2],
            popup=popup_str.format(lat2, lon2),
            icon=Icon(color="green")).add_to(map)
     map.save("map.html")
Beispiel #5
0
def build_map(trackpoint, trips):
    ''' Build and display Folium map '''
    html_file = args.output
    # color map for heatmap plugin
    heatmap_grad = \
        {0.0: '#000004',
         0.1: '#160b39',
         0.2: '#420a68',
         0.3: '#6a176e',
         0.4: '#932667',
         0.5: '#bc3754',
         0.6: '#dd513a',
         0.7: '#f37819',
         0.8: '#fca50a',
         0.9: '#f6d746',
         1.0: '#fcffa4'}

    fmap = Map(tiles='CartoDB dark_matter', prefer_canvas=True, max_zoom=16)

    # Individual coordonate as heatmap
    HeatMap(
        trackpoint,
        radius=5,
        blur=5,
        gradient=heatmap_grad,
        max_zoom=19).add_to(fmap)

    # Trace the trip as polyline
    for trip in trips:
        PolyLine(
            locations=trip,
            weight=5,
            color='#FFC300',
            opacity=0.6).add_to(fmap)

    # Set map bounds
    fmap.fit_bounds(fmap.get_bounds())

    # save map to HTML file and open with browser
    print('writing ' + html_file + '...')
    fmap.save(html_file)
    webbrowser.open(html_file, new=2, autoraise=True)
    print('done')
Beispiel #6
0
def walk(origin, destination, alternative):
    """
    Recoge las cordenadas y dibuja el mapa con direcciones
    (andando)
    """
    coordenadas = hi_google(origin, destination, alternative)
    distancia = coordenadas[0]
    mapa = Map(location=[coordenadas[2]["lat"], coordenadas[2]["lng"]],
               zoom_start=14)
    chincheta2 = Marker(
        location=[coordenadas[1]["lat"], coordenadas[1]["lng"]],
        tooltip="origen",
        popup="o")
    chinchetad = Marker(
        location=[coordenadas[2]["lat"], coordenadas[2]["lng"]],
        tooltip="destino",
        popup="d")
    chincheta2.add_to(mapa)
    chinchetad.add_to(mapa)
    PolyLine(coordenadas[3], color="red", weight=2.5, opacity=1).add_to(mapa)
    return mapa
 def get_line(self, **kwargs):
     return PolyLine(self.pings.values, tooltip=self.caption, **kwargs)
 def get_line(self, N=25, **kwargs):
     xy = self.data[self.GPS_INDEX].values    
     route = self.interpolate_great_circle(xy[0], xy[-1])
     return PolyLine(route, tooltip=self.caption, **kwargs)
 def get_line(self, **kwargs):
     xy = self.data[self.GPS_INDEX].values
     return PolyLine(xy, tooltip=self.caption, **kwargs)
Beispiel #10
0
import folium
from folium import PolyLine

initial_map = folium.Map(location=[-6.3728253, 34.8924826], zoom_start=5)

routes = [(-5.0889, 39.1023), (-6.7924, 39.2083), (-6.8278, 37.6591)]

PolyLine(routes, color='green', weight=10, opacity=0.5).add_to(initial_map)

initial_map.save('index.html')
Beispiel #11
0
# Making a map using generate_paths.
map4 = Map(location=center_point, zoom_start=12)

rc4 = RandomCoords(center=center_point, diameter=10, units='km')

for path in rc4.generate_paths(num_paths=15,
                               num_points_range=(10, 50),
                               circle_radius_range=(15, 25)):
    for point in path:
        CircleMarker(location=point,
                     radius=2,
                     color='blue',
                     fill=True,
                     fill_opacity=1).add_to(map4)
    PolyLine(locations=path, color='blue', weight=1).add_to(map4)

Circle(radius=5000, location=center_point, fill=False,
       color='red').add_to(map4)

map4.save(r'C:\Users\User\Desktop\path_map_km.html')

# Printing out the output for our RandomCoords objects as well as some sample output of the generate_coords function.
print('Object \'rc\' __str__ returns:')
print(rc, '\n')
print('Object \'rc2\' __str__ returns:')
print(rc2, '\n')
print('Object \'rc3\' __str__ returns:')
print(rc3, '\n')
print('Object \'rc4\' __str__ returns:')
print(rc4, '\n')
Beispiel #12
0
                       height=500,
                       control_scale=True)
        # m = folium.Map(location=[37.578,-57.728], tiles="OpenStreetMap", zoom_start=10,
        #                width=550, height=500, control_scale=True)
        gps_df_processed['normalized_counts'] = gps_df_processed[
            'counts'] / gps_df_processed['counts'].sum()
        stationArr = gps_df_processed[[
            'latitude', 'longitude', 'normalized_counts'
        ]].as_matrix().tolist()

        # print(stationArr)

        # # plot heatmap
        # colormap = cm.LinearColormap(['blue', 'lime', 'yellow', 'red'], index=[0.3, 0.5, 0.7, 1.0])
        # colormap.caption = 'A colormap caption'
        # m.add_child(colormap)
        # {0:'blue', 0.25:'green',0.75:'yellow', 1.0:'red'}
        m.add_child(
            HeatMap(stationArr,
                    gradient={
                        0.3: 'blue',
                        0.5: 'lime',
                        0.7: 'yellow',
                        1: 'red'
                    },
                    radius=0,
                    min_opacity=0.3,
                    blur=0))
        PolyLine(bounding_box, color="blue", weight=1, opacity=1).add_to(m)
        m.save(db_name + "_test.html")
Beispiel #13
0
def render(g,
           nodes,
           edges,
           file_name_out,
           markers=False,
           lines=False,
           host="localhost",
           port=5000,
           prefix=""):
    from limic.util import start, end, status, file_size
    from folium import Map, Marker, Icon, PolyLine
    from folium.plugins import BeautifyIcon
    from binascii import hexlify
    from pathlib import Path
    from math import log2
    from pkg_resources import resource_string
    start("Rendering graph")
    min_lat = min_long = float('inf')
    max_lat = max_long = -float('inf')
    for n in nodes:
        if n[1] < min_lat: min_lat = n[1]
        if n[2] < min_long: min_long = n[2]
        if n[1] > max_lat: max_lat = n[1]
        if n[2] > max_long: max_long = n[2]
    m = Map()
    m.fit_bounds([(min_lat, min_long), (max_lat, max_long)])
    if markers:
        for n in nodes:
            Marker(n[1:3],
                   icon=BeautifyIcon(icon='none',
                                     iconStyle="opacity: 0.1;",
                                     borderColor='#7f7f00',
                                     backgroundColor='#ffff00'),
                   tooltip=("id: %d" % n[0])).add_to(m)
    if lines:
        for u, v, weight in edges:
            PolyLine([u[1:3], v[1:3]],
                     color="#3f3f00",
                     opacity=0.4,
                     weight=6,
                     tooltip=("weight: %.1f" % weight)).add_to(m)
    TEMPLATE = resource_string("limic", "render.js").decode('utf8')
    from branca.element import MacroElement, Template

    class LatLngListener(MacroElement):
        _template = Template(TEMPLATE % {
            'host': host,
            'port': port,
            'prefix': prefix
        })

        def __init__(self):
            super(MacroElement, self).__init__()
            self._name = 'LatLngListener'

    LatLngListener().add_to(m)
    end()
    start("Saving result to HTML file", file_name_out)
    #m.save(file_name_out)
    end('')
    file_size(file_name_out)
    return g, nodes
Beispiel #14
0
def save_path(costpath, out_file=None, visualize=False):
    from sys import stdout
    if visualize and not out_file:
        status("WARNING (use --output to specify HTML file)   ", end='')
        visualize = False
    cost, path = costpath
    if visualize:
        from folium import Map, Marker, Icon, PolyLine
        from folium.plugins import BeautifyIcon
        from binascii import hexlify
        from webbrowser import open as wopen
        from pathlib import Path
        from math import log2
        min_lat = min_long = float('inf')
        max_lat = max_long = -float('inf')
        for x in path:
            if x[4] < min_lat: min_lat = x[4]
            if x[5] < min_long: min_long = x[5]
            if x[4] > max_lat: max_lat = x[4]
            if x[5] > max_long: max_long = x[5]
        m = Map()
        m.fit_bounds([(min_lat, min_long), (max_lat, max_long)])
        start_color = (63, 255, 63)
        end_color = (63, 63, 255)
        diff_color = tuple(
            map(lambda x: x[0] - x[1], zip(end_color, start_color)))
        length = float(len(path))
        for i in range(len(path)):
            x = path[i]
            background_color = "#" + hexlify(
                bytes(
                    map(lambda x: int(x[0] + i * x[1] / length),
                        zip(start_color, diff_color)))).decode('utf8')
            border_color = "#" + hexlify(
                bytes(
                    map(lambda x: int((x[0] + i * x[1] / length) / 2),
                        zip(start_color, diff_color)))).decode('utf8')
            line_color = background_color
            line_weight = 6
            icon = None
            iconStyle = ""
            if x[3] < 0:
                icon = 'times'
                background_color = "#ffff3f"
                border_color = "#7f1f1f"
            elif x[2]:
                icon = 'flash'
                background_color = "#ff0000"
                border_color = "#7f0000"
                line_color = background_color
                line_weight = 10
            elif i + 1 < len(path) and path[i + 1][2]:
                icon = 'flash'
                background_color = "#ff0000"
                border_color = "#7f0000"
            elif i == 0 or i + 1 == len(path):
                icon = 'flash'
            else:
                icon = 'none'
                iconStyle = "opacity: 0.1;"
            if i > 0 and cost is not None:
                PolyLine([path[i - 1][4:6], path[i][4:6]],
                         color=line_color,
                         opacity=0.4,
                         weight=line_weight).add_to(m)
            if icon:
                Marker(x[4:6],
                       icon=BeautifyIcon(icon=icon,
                                         iconStyle=iconStyle,
                                         borderColor=border_color,
                                         backgroundColor=background_color),
                       popup=("cost: %.1fm, dist: %.1fm, air: %r, id: %d" %
                              x[:4])).add_to(m)
        m.save(out_file)
        wopen(Path(out_file).resolve().as_uri(), new=2)
    else:
        file = open(out_file, "w") if out_file else stdout
        print("node(id:" + ",".join(map(lambda x: str(x[3]), path)) + ");out;",
              file=file)