Exemplo n.º 1
0
def build_ski_marker(location,
                     data,
                     width=475,
                     height=250,
                     icon_color='#966fd6',
                     chart_kw={}):

    centroid = data[['latitude', 'longitude']].iloc[0].values
    tooltip = 'Skiing in {:s}'.format(location)
    chart = build_ski_chart(location,
                            data,
                            width=width - 75,
                            height=height - 25,
                            **chart_kw)

    popup = Popup(max_width=width).add_child(
        VegaLite(chart.to_json(), width=width, height=height))

    icon_kw = dict(icon_shape='circle',
                   border_width=0,
                   text_color='white',
                   border_color='white',
                   background_color='black',
                   inner_icon_style='font-size:11px; padding-top: 1px;')

    icon = BeautifyIcon('line-chart', **icon_kw)

    marker = Marker(location=centroid, icon=icon, tooltip=tooltip, popup=popup)

    return marker
Exemplo n.º 2
0
 def _folium_kwargs(self):
     attrs = self._attrs.copy()
     attrs['location'] = self.lat_lon
     icon_args = {
         k: attrs.pop(k)
         for k in attrs.keys() & {
             'color', 'marker_icon', 'clustered_marker', 'icon_angle',
             'popup_width'
         }
     }
     if 'marker_icon' in icon_args:
         icon_args['icon'] = icon_args.pop('marker_icon')
     if 'color' in icon_args and icon_args['color'][0] == '#':
         # Checks if color provided is a hex code instead; if it is, uses BeautifyIcon to create markers.
         # If statement does not check to see if color is an empty string.
         icon_args['background_color'] = icon_args[
             'border_color'] = icon_args.pop('color')
         if icon_args['background_color'][1] == icon_args[
                 'background_color'][3] == icon_args['background_color'][
                     5] == 'f':
             icon_args['text_color'] = 'gray'
         else:
             icon_args['text_color'] = 'white'
         icon_args['icon_shape'] = 'marker'
         if 'icon' not in icon_args:
             icon_args['icon'] = 'circle'
         attrs['icon'] = BeautifyIcon(**icon_args)
     else:
         attrs['icon'] = folium.Icon(**icon_args)
     return attrs
Exemplo n.º 3
0
    def get_marker(self,
                   width=450,
                   height=250,
                   icon_color='#966fd6',
                   chart_kw={}):

        chart = self.build_chart(width=width - 75,
                                 height=height - 25,
                                 **chart_kw)

        popup = Popup(max_width=width).add_child(
            VegaLite(chart.to_json(), width=width, height=height))

        icon_kw = dict(icon_shape='circle',
                       border_width=0,
                       text_color='white',
                       border_color='white',
                       background_color='green',
                       inner_icon_style='font-size:11px; padding-top: 1px;')

        icon = BeautifyIcon('line-chart', **icon_kw)

        location = self.data.iloc[0][['latitude', 'longitude']].values

        marker = Marker(location=location,
                        icon=icon,
                        tooltip=self.semantic,
                        popup=popup)

        return marker
Exemplo n.º 4
0
    def add_photos_to_map(self,
                          clustered=True,
                          maxClusterRadius=20,
                          disableClusteringAtZoom=15,
                          zoomToBoundsOnClick=False,
                          spiderfyOnMaxZoom=True,
                          icon_color='#b3334f',
                          groupby=None,
                          **kwargs):

        # add feature group
        self.fgs['photos'] = FeatureGroup('Photos', show=True).add_to(self.map)

        # create photo cluster object
        if clustered:
            dst = MarkerCluster(
                maxClusterRadius=maxClusterRadius,
                disableClusteringAtZoom=disableClusteringAtZoom,
                showCoverageOnHover=False,
                zoomToBoundsOnClick=zoomToBoundsOnClick,
                spiderfyOnMaxZoom=spiderfyOnMaxZoom,
                **kwargs).add_to(self.fgs['photos'])
        else:
            dst = self.fgs['photos']

        # add photos to cluster object
        for idx, photo in self.photos.iterrows():
            xy = photo[self.GPS_INDEX].values.astype(float)

            if groupby is not None:
                gallery = photo[groupby]
            else:
                gallery = None

            popup = ImagePopup(photo.imgur_id,
                               caption=photo.caption,
                               aspect=photo.image_aspect,
                               gallery=gallery).popup

            icon = BeautifyIcon(
                'camera',
                border_width=0,
                text_color=icon_color,
                border_color=icon_color,
                background_color='transparent',
                inner_icon_style='font-size:20px;padding-top:-1px;')

            Marker(
                xy,
                popup=popup,
                tooltip=photo.caption,
                icon=icon,
            ).add_to(dst)
def show_map(request):
    #creation of map comes here + business logic
    try:
        a = request.session['logged']
    except KeyError:
        request.session['logged'] = False
    if request.session['logged']:
        user = userBase.objects.filter(mail=request.session['mail']).get()
        store = magBase.objects.values_list('adress', flat=True)
        store = list(store)
        m = folium.Map(
            location=[user.lat, user.lon],
            zoom_start=15,
            tiles='Stamen Terrain',
            min_zoom=8,
            width=1200, height=600
        )
        folium.TileLayer('openstreetmap').add_to(m)
        number_icon = BeautifyIcon(icon='angle-double-down', icon_shape='marker',text_color="#000", border_color="transparent",
            background_color="#22F", inner_icon_style="font-size:12px;padding-top:-5px;") 
        folium.Marker(
            location=[user.lat, user.lon],
            popup=folium.Popup(str(user.adress+'\nChez vous'), width=200),
            icon=number_icon).add_to(m)
        for item in store:
            mag = magBase.objects.filter(adress=item).first()
            number_icon = BeautifyIcon(icon='angle-double-down', icon_shape='marker',text_color="#000", border_color="transparent",
            background_color="#2D2", inner_icon_style="font-size:12px;padding-top:-5px;") 
            folium.Marker(
                location=[funcs.getlat_fadress(item), funcs.getlon_fadress(item)],
                popup=folium.Popup(str(item + '\n' + mag.name), width=200),
                icon=number_icon).add_to(m)
        m=m._repr_html_() #updated
        context = {'my_map': m}
        return render(request, 'map/map.html', context)
    else:
        return render(request, 'map/access.html')
Exemplo n.º 6
0
def draw_along_search_map(res, points, max_res_limit):
    """Function to draw returned result of along_search service on map"""

    # draw home, destination, shortest route between them
    tomtom_map = draw_route(points)

    # create heat colors scale for markers to show Priority of the place
    # we chose here blue gradients
    colors = list(Color("#000080").range_to(Color("#d5e5ff"), max_res_limit))

    # for each returened place
    for ind, poi in enumerate(res['results']):

        # calculate detour time for this place in minutes
        detour_h, detour_min = convert_sec_to_h_m(poi['detourTime'], False)

        #print(poi['detourTime'])
        # create marker on the place has own size and color
        icon_ = BeautifyIcon(
            icon_shape='marker',
            number=ind + 1,
            spin=True,
            text_color='gray',
            icon_size=(40 - ind, 40 - ind),
            border_color=str(colors[ind]),
            background_color=str(colors[ind]),
            inner_icon_style="font-size:12px;padding-top:-5px;")

        # add a marker for each lat, lon
        folium.Marker(
            location=tuple(poi['position'].values()),
            popup=folium.Popup(
                f"<b>{poi['poi']['name']}</b> <br>{poi.get('address').get('streetName','')}, {poi['address']['municipalitySubdivision']}",
                max_width=100),
            icon=icon_,
            tooltip=f"<b>{poi['poi']['name']}</b> <br> ({detour_min} mins)"
        ).add_to(tomtom_map)
    return tomtom_map
Exemplo n.º 7
0
def plot_map(geolocator, best_guess, coordinates, addresses, shops_names,
             n_shops):
    #location = geolocator.geocode("Rio de Janeiro, RJ, Brazil")
    m = folium.Map(location=[-22.9385, -43.4060], zoom_start=11)

    for ix, i in enumerate(best_guess):
        popup = 'None'
        color = '#000000'

        if ix == 0:
            popup = folium.Popup('Origem')
            color = '#000000'
        elif i > 0 and i <= n_shops:
            popup = folium.Popup(
                '{}a Parada<br>Abastecimento na Loja {}'.format(
                    ix, shops_names[i - 1]),
                max_width=200)
            color = '#2ca02c'
        else:
            popup = folium.Popup('{}a Parada<br>Entrega da Loja {}'.format(
                ix, shops_names[i - 1]),
                                 max_width=200)
            color = '#BA3CC2'

        icon_number = BeautifyIcon(border_color=color,
                                   text_color='#000000',
                                   number=ix,
                                   icon_size=[30, 30],
                                   inner_icon_style='margin_top:10;')

        folium.Marker(location=[coordinates[i][0], coordinates[i][1]],
                      popup=popup,
                      tooltip=addresses[i],
                      icon=icon_number).add_to(m)

    return m
                    color_by='velocity-level',
                    cmap='RdYlGn_09',
                    line_options=line_options2,
                    add_start_end=False)
 # Find 1 km locations:
 maxd = max(segment['Distance / km'])
 locations = np.arange(1, maxd, 1)
 location_idx = []
 for j in locations:
     diff = abs(j - segment['Distance / km'])
     idx = np.argmin(diff)
     location_idx.append(idx)
 for dist, j in zip(locations, location_idx):
     icon = BeautifyIcon(text_color='#262626',
                         border_color='#006d2c',
                         background_color='#ffffff',
                         number=dist,
                         icon_shape='marker',
                         border_width=3)
     marker = folium.Marker(
         location=segment['latlon'][j],
         icon=icon,
         tooltip=f'{dist} km',
         popup=f'{segment["time"][j].strftime("%H:%M:%S")}',
     )
     marker.add_to(the_map)
 # Add end marker:
 marker = folium.Marker(
     location=segment['latlon'][-1],
     icon=folium.Icon(icon='home'),
     tooltip=f'{segment["Distance / km"][-1]:.2f} km',
     popup=f'{segment["time"][i].strftime("%H:%M:%S")}',
def lanza_mapa(self, dataframe, ruta_carpeta,from_excel=False):
    colores=('blue','pink','orange','red','purple','yellow','green','brown','grey')
    id_vehiculo=str(dataframe.index[0])
    ruta_carpeta_vehiculo = ruta_carpeta+"\\vehiculo_{}".format(id_vehiculo)
    if not os.path.exists(ruta_carpeta_vehiculo):
        os.makedirs(ruta_carpeta_vehiculo)
    WINDOW_SIZE = "680,530"
    chrome_options = Options()  
    chrome_options.add_argument("--headless")  
    chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
    
#    chrome_options.binary_location = CHROME_PATH
    #creamos 2 ventanas una para el cargando y otra para mostrar las pestañas
    ventana_mapas = tk.Toplevel()
    ventana_mapas.withdraw()
    ventana_carga= tk.Toplevel()
    tk.Label(ventana_carga, text='Cargando mapas').pack()
    ventana_carga.update()
    ventana_mapas.title("Maps vehicle " + id_vehiculo)
    pestañas = Notebook(ventana_mapas)
    # cargamos el selenium que de fondo va a renderizar los mapas 
    driver = selenium.webdriver.Chrome(chrome_options=chrome_options)
    #cargamos el geojson de base
    #geojson= r"C:\Users\Andrés\Desktop\mapa2.geojson"
    geojson= r"D:\Documentos\GitHub\Aparcamientos-visualizacion---py\mapa.geojson"
    
    dataframe_partida = dataframe
    
#    dataframe_partida.set_index('ID', inplace=True, drop = False)
    
    #cargamos los puntos medios de las calles y los puntos iniciales y finales para el path
    calles_medio= pd.read_excel(r"D:\Documentos\GitHub\Aparcamientos-visualizacion---py\calles_medios.xls")
    calles_medio.set_index('Name', inplace=True)
    calles_inicio= pd.read_excel(r"D:\Documentos\GitHub\Aparcamientos-visualizacion---py\calles_inicios.xls")
    calles_inicio.set_index('Name', inplace=True)
    calles_fin= pd.read_excel(r"D:\Documentos\GitHub\Aparcamientos-visualizacion---py\calles_finales.xls")
    calles_fin.set_index('Name', inplace=True)
    
    id_coche=id_vehiculo
    
    #cargamos las secciones donde ha intentado aparcar
    print(type(dataframe_partida['Secciones intento aparcamiento']))
    print(dataframe_partida['Secciones intento aparcamiento'])
    if from_excel:
        secciones_intento=ast.literal_eval(dataframe_partida['Secciones intento aparcamiento'])
        utilidades=dataframe_partida['Utilidades iteraciones'].replace("L","").replace("nan","-999")
        utilidades=ast.literal_eval(utilidades)
        tracks_pintar=ast.literal_eval(dataframe_partida['track_secciones'])
    else:
        secciones_intento=dataframe_partida['Secciones intento aparcamiento']#
        utilidades=dataframe_partida['Utilidades iteraciones']#ast.literal_eval(utilidades)
        tracks_pintar=dataframe_partida['track_secciones']#ast.literal_eval(dataframe_partida['track_secciones'])
    marcadores=[]
    tracks_seguidos=[]
    seccion_de_paso= dataframe_partida['Seccion de paso']=='si'
    if seccion_de_paso:
        utilidades=utilidades[:-1]
    for elemento,iteracion in zip(utilidades, count(0)):  
        #marco ventanas
        marco=Frame(pestañas)
        #se carga el mapa centrado en la zona ded estudio
        m = folium.Map(location=[43.463872, -3.798428], zoom_start=17,tiles='cartodbpositron')
        
        #extraemos el nodo final de aparcamiento y de destino así como el de intento de esta iteración
        aparcamiento=dataframe_partida['Nodo aparcamiento']
        destino=dataframe_partida['Nodo destino']
        intento_aparcamiento=secciones_intento[iteracion]
        
        #marcador final parking
        folium.Marker([calles_medio.loc[aparcamiento,'lat'], calles_medio.loc[aparcamiento,'long']], tooltip="Parking final", permanent=True,icon=folium.Icon(color='black')).add_to(m)
        
        #ponemos los marcadores de los sitios de paso el destino
        folium.Marker([calles_medio.loc[destino,'lat'], calles_medio.loc[destino,'long']], tooltip="Destino", permanent=True,icon=folium.Icon(color='green')).add_to(m)
#        folium.Marker([calles_medio.loc[aparcamiento,'lat'], calles_medio.loc[aparcamiento,'long']], tooltip="Aparcamiento",icon=folium.Icon(color='red')).add_to(m)
        
        marcador_paso=folium.Marker([calles_medio.loc[intento_aparcamiento,'lat'], calles_medio.loc[intento_aparcamiento,'long']], tooltip="Intento {}".format(str(iteracion)),permanent=True,icon=folium.Icon(color='blue'))    
        BeautifyIcon(number=iteracion+1, icon_shape='marker',border_color='blue').add_to(marcador_paso)
        marcadores.append(marcador_paso)
        for x in marcadores:
            x.add_to(m)
        
        #se manipula el df de utilidades y se pinta haciendo una capa nueva 
        utilidades_fin=pd.DataFrame.from_dict(elemento['utilidades'], columns=[ 'util'],orient='index')
        utilidades_fin.reset_index(inplace=True)
        utilidades_fin['index']=utilidades_fin['index'].apply(lambda x: str(x))
        utilidades_fin.replace(-999,np.nan, inplace=True)
        folium.Choropleth(
            geo_data=geojson,
            data=utilidades_fin,
            columns=['index', 'util'],
            key_on='feature.properties.Name',
            fill_color='OrRd',
            legend_name='Utility',
        ).add_to(m)
        
        #cogemos el track del vehiculo que estamos siguiendo
        track_total=[]
        for seccion in tracks_pintar[iteracion]:
            track_total.append((calles_inicio.loc[seccion,'lat'],calles_inicio.loc[seccion,'long']))
            track_total.append((calles_fin.loc[seccion,'lat'],calles_fin.loc[seccion,'long']))    
        track_iter=AntPath(tuple(track_total),color= colores[iteracion])
        tracks_seguidos.append(track_iter)
        for viaje in tracks_seguidos:
            viaje.add_to(m)
        
        
        # se guarda el mapa y se saca el pantallazo
        ruta_mapa=ruta_carpeta_vehiculo+'mapa{}.html'.format(str(iteracion))
        m.save(ruta_mapa) 
        driver.get(ruta_mapa)
        ruta_imagen=ruta_carpeta_vehiculo+'\\screenshot{}.png'.format(str(iteracion))
        driver.save_screenshot(ruta_imagen)
        print(ruta_imagen)
        #añadimos una pestaña con el pantallazo y el enlace al mapa
        img = ImageTk.PhotoImage(Image.open(ruta_imagen))
        label=tk.Label(marco,text=ruta_imagen, image=img)
        label.image=img
        label.pack()
        tk.Label(marco,text='For a better user experience open maps in browser is recomended').pack()
        tk.Button(marco, text="Open map in browser",
                  command= lambda : webbrowser.open(ruta_mapa, new=2)).pack()
        pestañas.add(marco, text="Iteration {}".format(str(iteracion)), padding=10)
    
    
    driver.close()
    pestañas.pack(padx=10, pady=10)
    ventana_carga.destroy()
    ventana_mapas.deiconify()
Exemplo n.º 10
0
    def add_travel_to_map(self,
                          flight_color='darkred',
                          train_color='green',
                          drive_color='black',
                          weight=3,
                          show=False,
                          drive_kwargs={}):

        # add feature group
        if self.trip_ids is not None:
            for trip_id in self.trip_ids:
                self.fgs[trip_id] = FeatureGroup(trip_id,
                                                 show=show).add_to(self.map)

        # add start/finish
        icon_kw = dict(icon_shape='marker',
                       border_width=2,
                       text_color='black',
                       border_color='black',
                       background_color='white',
                       inner_icon_style='font-size:14px; padding-top:-1px;')
        start, finish = self.bounds

        # add segments
        arrived = {k: False for k in self.trip_ids}
        for flight in self.air:

            for trip_id in flight.trip_ids:

                if trip_id not in self.fgs.keys():
                    continue

                if not arrived[trip_id] or trip_id == 'Return Flights':

                    arrived[trip_id] = True
                    for leg in flight.legs:

                        obj = leg.get_line(color=flight_color,
                                           weight=weight,
                                           opacity=0.5).add_to(
                                               self.fgs[trip_id])

                        if leg.is_connection:
                            tooltip = 'Layover in {:s}'.format(
                                leg.destination_str)
                        else:
                            tooltip = 'Arriving from {:s}'.format(
                                leg.origin_str)

                        # arrival icon
                        _ = Marker(
                            leg.destination[flight.GPS_INDEX].values,
                            icon=BeautifyIcon('arrow-down', **icon_kw),
                            tooltip=tooltip,
                        ).add_to(self.fgs[trip_id])

                else:

                    # departure icon
                    _ = Marker(
                        flight.origin[flight.GPS_INDEX].values,
                        icon=BeautifyIcon('plane', **icon_kw),
                        tooltip='Departing to {:s}'.format(
                            flight.destination_str),
                    ).add_to(self.fgs[trip_id])

        for train in self.rail:
            for trip_id in train.trip_ids:
                if trip_id not in self.fgs.keys():
                    continue
                obj = train.get_antpath(color=train_color,
                                        weight=weight,
                                        opacity=0.5)
                obj.add_to(self.fgs[trip_id])

        for drive in self.land:

            for trip_id in drive.trip_ids:
                if trip_id not in self.fgs.keys():
                    continue

                options = {'smoothFactor': 10}
                try:
                    obj = drive.get_antpath(color=drive_color,
                                            weight=weight,
                                            options=options,
                                            **drive_kwargs)
                    obj.add_to(self.fgs[trip_id])
                except:
                    print('No drive segments found in {:s}'.format(
                        drive.caption))
Exemplo n.º 11
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
Exemplo n.º 12
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)
Exemplo n.º 13
0
print("Plotting Map...")
m = Map(location=[0, 0], zoom_start=2)

for index, row in poi_list.iterrows():
    color = "#%06x" % random.randint(0, 0xFFFFFF)
    if row["Count"] > 0:
        Circle(
            location = (row["Latitude"], row["Longitude"]),
            radius = int(row["MaximumDistance"]),
            color = color,
            fill_color = color
        ).add_to(m)
        Marker(
            location=[row["Latitude"], row["Longitude"]],
            popup=Popup(row["POIID"] + ", Popularity: " + "{0:.2f}".format(row["Popularity"]) + ", Count: " + "{0:.0f}".format(row["Count"]), sticky=True, show=True),
            icon=BeautifyIcon(background_color=color, icon='marker'),
            draggable=False
        ).add_to(m)    


marker_cluster = MarkerCluster().add_to(m)

for index, row in without_duplicates.iterrows():
    Marker(
        location=[row["Latitude"], row["Longitude"]],
        popup= "Nearest POI: " + row["POI"],
        # icon=Icon(color='green', icon='ok-sign'),
        draggable=False
    ).add_to(marker_cluster)

outfp = "output/basemap.html"
def add_dwelling_marker_to_map(m, dwelling, icon_type):
    x, y = parse_geometry(dwelling['geometry'])
    lon, lat = rijksdriehoek_to_wsg84(x, y)

    def percentage(key):
        return f'{dwelling[key] * 100:.1f}%'

    def numeric_range(key):
        mean = dwelling[f'{key}_mean']
        range_ = dwelling[f'{key}_95']

        if type(range_) == str:
            lower = range_.replace('[', '').replace(']', '').split(',')[0]
            upper = range_.replace('[', '').replace(']', '').split(',')[1]
            return f'{mean} (95%: {lower} to {upper})'
        else:
            lower = range_.lower
            upper = range_.upper
            return f'{mean:.1f} (95%: {lower:.1f} to {upper:.1f})'

    results = {
        'Base data': {
            'vbo ID':
            f"<samp>{dwelling['vbo_id']}</samp>",
            'coordinates':
            f'({lon:.2f}, {lat:.2f})',
            'construction year':
            dwelling['bouwjaar'],
            'surface area':
            f"{dwelling['oppervlakte']} m<sup>2</sup>",
            'dwelling type':
            f"{dwelling['woningtype'].replace('_', ' ')}",
            'neighbourhood':
            f"{dwelling['buurt_name']} (<samp>{dwelling['buurt_id']}</samp>)"
        },
        'Energy label': {
            'measured': dwelling['energy_label_class'],
            'predicted': numeric_range('energy_label_class')
        },
        'Space heating': {
            'district heating': percentage('district_heating_space_p'),
            'block heating': percentage('block_heating_space_p'),
            'gas boiler': percentage('gas_boiler_space_p'),
            'electric boiler': percentage('elec_boiler_space_p'),
            'hybrid heat pump': percentage('hybrid_heat_pump_p'),
            'electric heat pump': percentage('electric_heat_pump_p')
        },
        'Water heating': {
            'district heating': percentage('district_heating_water_p'),
            'block heating': percentage('block_heating_water_p'),
            'gas boiler': percentage('gas_boiler_water_p'),
            'electric boiler': percentage('elec_boiler_water_p'),
            'electric heat pump': percentage('electric_heat_pump_water_p')
        },
        'Cooking': {
            'gas': percentage('gas_cooking_p'),
            'electric': percentage('electric_cooking_p')
        },
        'Insulation': {
            'facade R': numeric_range('insulation_facade_r'),
            'roof R': numeric_range('insulation_roof_r'),
            'floor R': numeric_range('insulation_floor_r'),
            'windows R': numeric_range('insulation_window_r')
        }
    }

    table = '<table>'
    for key, val in results.items():

        for index, (key_2, val_2) in enumerate(val.items()):
            table += f'<tr class="{"new-cat" if index == 0 else ""}">\n'
            table += f'\t<td>{key if index == 0 else ""}</td>\n'
            table += f'\t<td>{key_2}</td>\n'
            table += f'\t<td>{val_2}</td>\n'
            table += '</tr>\n'
    table += '</table>'

    style = '''
	<style>
	* {
		font-size: 16px;
		font-family: -apple-system, BlinkMacSystemFont, sans-serif
	}
	td {
		padding-top: 5px;
		padding-right: 20px;
	}
	tr.new-cat > td {
		padding-top: 15px
	}
	td:nth-child(1) { font-weight: bold }
	td:nth-child(2) { font-weight: bold; text-align: right; }
	td:nth-child(3) { }
	</style>
	'''

    html = f'''
	{style}
	<div style="width: 45vw; height: 70vh; position: relative">
		<div style="border-bottom: 2px solid #ddd; margin-bottom: 10px">
			<h3>Dwelling: {dwelling['adres'].replace('_', ' ')}</h3>
		</div>
		<div style='overflow-y: auto; height: 90%'>
			{table}
		</div>
	</div>
	'''

    my_popup = folium.Popup(html)
    if icon_type == 'house':
        icon = folium.Icon(icon='home', prefix='fa')
    else:
        icon = BeautifyIcon(
            icon_shape='circle-dot',
            border_color=get_energy_label_colour(dwelling),
            border_width=4,
        )

    folium.Marker((lon, lat), popup=my_popup, icon=icon).add_to(m)
Exemplo n.º 15
0
    parse_dates=["Open_From", "Open_To"]
)

# Plot the locations on the map with more info in the ToolTip
for location in deliveries_data.itertuples():
    tooltip = folium.map.Tooltip("<h4><b>ID {}</b></p><p>Supplies needed: <b>{}</b></p>".format(
        location.Index, location.Needed_Amount
    ))

    folium.Marker(
        location=[location.Lat, location.Lon],
        tooltip=tooltip,
        icon=BeautifyIcon(
            icon_shape='marker',
            number=int(location.Index),
            spin=True,
            text_color='red',
            background_color="#FFF",
            inner_icon_style="font-size:12px;padding-top:-5px;"
        )
    ).add_to(m)

# The vehicles are all located at the port of Beira
depot = [-19.818474, 34.835447]

folium.Marker(
    location=depot,
    icon=folium.Icon(color="green", icon="bus", prefix='fa'),
    setZIndexOffset=1000
).add_to(m)

m
Exemplo n.º 16
0
tloc = tloc.drop(tloc.index[0])
tloc[["Latitute", "Longitude"]] = tloc[["Latitute",
                                        "Longitude"]].apply(pd.to_numeric)
tloc = tloc[tloc['Latitute'].notnull()]

mc2 = MarkerCluster(icon_create_function=icon_create_function_test)
# plot testing center data
testing_feature = FeatureGroup(name='Testing Centers')
for row in tloc.itertuples():
    # folium.Marker((row.Latitute, row.Longitude), popup=folium.Popup('<a href="%s" target="_blank"> %s </a>' %
    # (row.URL, row._2)), icon=folium.Icon(color='lightblue', icon='medkit', prefix='fa')).add_to(testing_feature)
    folium.Marker((row.Latitute, row.Longitude),
                  popup=folium.Popup('<a href="%s" target="_blank"> %s </a>' %
                                     (row.URL, row._2)),
                  icon=BeautifyIcon(icon='medkit',
                                    icon_shape='marker',
                                    background_color="#009FDC")).add_to(mc2)
mc2.add_to(testing_feature)
testing_feature.add_to(covid_map)

# ------------- plot traffic ------- #

# testing_traffic = FeatureGroup(name='Present Traffic')

# # CO cellphone data
# codf = pd.read_csv('https://raw.githubusercontent.com/nthakor/imghost/master/denver-06-16-1100-1159.csv')
# for i, row in codf.iterrows():
#     folium.Marker(location=[row.lat1, row.lon1],
#                   icon=BeautifyIcon(icon='car')).add_to(testing_traffic)
# # MD cellphone data
# mddf1 = pd.read_csv(