Exemple #1
0
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Folium Map')
        self.showMaximized()

        layout = QVBoxLayout()
        self.setLayout(layout)

        coordinate = (39.99999021143304400, 34.50000978856695600)
        m = folium.Map(tiles='openstreetmap',
                       zoom_start=13,
                       location=coordinate,
                       control_scale=True,
                       prefer_canvas=True)

        folium.Marker(coordinate,
                      popup='IKA',
                      icon=folium.Icon(icon="arrow-down")).add_to(
                          m)  #harita üzerinde mark eklemek için kullanılır.

        folium.Circle(
            radius=5000,
            location=coordinate,
            color='crimson',
            fill=False,
        ).add_to(m)  #harita üzerinde yuvarlak çizmek için kullanılır.

        folium.CircleMarker(location=coordinate, radius=100,
                            fill_color='red').add_to(
                                m)  #dinamik bi circle çizer

        minimap = plugins.MiniMap(position="topleft", width=250, height=250)
        m.add_child(minimap)
Exemple #2
0
def create_distribution_heatmap(name: str, lats: list, lons: list):
    """Create a folonium distribution heatmap.
    It plots a point for every couple of latitude and longitude given
    """
    url_base = "http://server.arcgisonline.com/ArcGIS/rest/services/"
    service = "NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}"
    tileset = url_base + service

    heatmap_map = folium.Map(
        location=france_location,
        zoom_start=2,
        control_scale=True,
        tiles=tileset,
        attr="USGS style",
    )
    data = [lon_lat for lon_lat in zip(lats, lons)]

    heatmap_map.add_child(plugins.HeatMap(data))
    heatmap_map.add_child(plugins.MeasureControl())
    heatmap_map.add_child(
        plugins.Fullscreen(
            position="topright",
            title="Expand me",
            title_cancel="Exit me",
            force_separate_button=True,
        )
    )
    heatmap_map.add_child(plugins.MeasureControl())
    heatmap_map.add_child(plugins.MiniMap())
    save_map(heatmap_map, name)
Exemple #3
0
def _add_map_controls(map_instance,
                      minimap=True,
                      mouse_position=True,
                      measure_controll=True,
                      draw=True):
    """Add aditional map controlls and features to the map\n
    map_instance: The map instance that was used to initialize the add_map() function\n
    minimap: Add minimap in the bottom left\n
    mouse_position: Coordinate information on hover\n
    measure_controll: adds a feature that allows the user to measure distance on the map\n
    draw: Adds the ability to draw different geometries on a map and save it as geojson
    \nexample:\n
    m = add_map(data= gdf)\n
    add_layer(data= gdf, color_column= 'color_values').add_to(m)\n
    add_map_controls(m)
    m.save('my_map.html') #Used when needing to plot large amounts of data which notebook can't handle
    """

    map_instance = map_instance
    folium.TileLayer('OpenStreetMap').add_to(map_instance)
    folium.TileLayer('CartoDB dark_matter').add_to(map_instance)
    folium.TileLayer('CartoDB positron').add_to(map_instance)
    folium.LayerControl().add_to(map_instance)

    plugins.Fullscreen(position='topleft',
                       title='Expand me',
                       title_cancel='Exit me',
                       force_separate_button=False).add_to(map_instance)

    if minimap:
        plugins.MiniMap(tile_layer='OpenStreetMap',
                        position='bottomleft',
                        toggle_display=True,
                        minimized=False).add_to(map_instance)
    else:
        pass

    if mouse_position:
        fmtr = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};"
        plugins.MousePosition(position='bottomleft',
                              separator=' | ',
                              prefix="Mouse:",
                              lat_formatter=fmtr,
                              lng_formatter=fmtr).add_to(map_instance)
    else:
        pass

    if measure_controll:
        plugins.MeasureControl(secondary_length_unit='kilometers',
                               secondary_area_unit='sqkilometers',
                               position='bottomright').add_to(map_instance)
    else:
        pass

    if draw:
        plugins.Draw(export=True).add_to(map_instance)
    else:
        pass

    return (map_instance)
def create_map(dictionary):
    """
    (None) -> None

    Create a map with folium in HTML file
    Add: map, locations, clusters, population colour, mini map, layer control
    """
    map = folium.Map([45, 3], zoom_start=2)
    # ADD MARKERS
    fg = add_markers(dictionary)
    # ADD BOUNDARIES
    population_mask = add_boundaries()
    # ADD CLASTERS
    clusters = add_clusters(dictionary)
    # MINI MAP
    minimap = plugins.MiniMap()
    # ADD ALL CHILDS
    map.add_child(fg)
    map.add_child(population_mask)
    map.add_child(clusters)
    map.add_child(minimap)
    # to tick/untick the whole group put things
    # in LC and handle them as a single layer
    map.add_child(folium.LayerControl())
    map.save('./docs/index.html')
    webbrowser.open("./docs/index.html")
Exemple #5
0
def open_webb_and_save(mapka, fileHtml):
    folium.raster_layers.TileLayer('Open Street Map').add_to(mapka)
    folium.raster_layers.TileLayer('StamenTerrain').add_to(mapka)
    folium.raster_layers.TileLayer('CartoDB Positron').add_to(mapka)
    folium.raster_layers.TileLayer('StamenToner').add_to(mapka)
    folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(mapka)
    folium.raster_layers.TileLayer('Stamen Watercolor').add_to(mapka)
    folium.LayerControl().add_to(mapka)

    minimap = plugins.MiniMap(toggle_display=True)
    mapka.add_child(minimap)

    plugins.Fullscreen(position='topright').add_to(mapka)
    measureControl = plugins.MeasureControl(position='topleft',
                                            active_color='red',
                                            completed_color='red',
                                            primary_length_unit='km')
    mapka.add_child(measureControl)
    draw = plugins.Draw(position='topleft', export='True')
    draw.add_to(mapka)

    html_page = f'{fileHtml}'
    mapka.save(fileHtml)
    mapka.save(html_page)
    new = 2
    webbrowser.open(html_page, new=new)
    tkinter.messagebox.showinfo("Analiza gpx",
                                "Zakończono analizę pliku i dołączono mapę")
Exemple #6
0
def test_minimap():
    m = folium.Map(location=(30, 20), zoom_start=4)

    minimap = plugins.MiniMap()
    m.add_child(minimap)

    out = normalize(m._parent.render())

    # Verify that a new minimap is getting created.
    assert 'new L.Control.MiniMap' in out

    m = folium.Map(location=(30, 20), zoom_start=4)
    minimap = plugins.MiniMap(tile_layer="Stamen Toner")
    minimap.add_to(m)

    out = normalize(m._parent.render())
    # verify that Stamen Toner tiles are being used
    assert 'https://stamen-tiles' in out
Exemple #7
0
def create_map():
    '''
    Function for creating a map
    :return: None
    '''

    points = points_feat.create_points(flask_path)
    # points = points_feat.create_points(main_path)
    FEATURES = points['features']
    print(FEATURES)
    points_COORDINATES = points['coordinates']
    DEF_TIME = points['set-time']

    folium_map = folium.Map(location=[40.738, -73.98],
                            zoom_start=12,
                            tiles="CartoDB dark_matter")

    # MiniMap plugin
    minimap = plugins.MiniMap()
    folium_map.add_child(minimap)

    # Fullscreen plugin
    plugins.Fullscreen(position='topright',
                       title='Expand me',
                       title_cancel='Exit me',
                       force_separate_button=True).add_to(folium_map)

    # Timestamp plugin
    plugins.TimestampedGeoJson(
        {
            'type': 'FeatureCollection',
            'features': FEATURES
        },
        period='PT4H',
        add_last_point=True).add_to(folium_map)

    COORDINATES = []
    for c in points_COORDINATES:
        newlst = [c[1], c[0]]
        aqi = pollution.get_air_data(newlst, DEF_TIME)[0] / 2.5
        newlst.append(aqi)
        COORDINATES.append(newlst)
    print(COORDINATES)

    heat_map = plugins.HeatMap(COORDINATES, radius=50)
    heat_map.layer_name = 'Air Quality'
    folium_map.add_child(heat_map)

    folium_map.add_child(folium.LayerControl())

    print('> Done.')
    folium_map.save("../NY_MAP/templates/my_map.html")
def gerar_mapa(request):

    ip = get('https://api.ipify.org').text
    response1 = DbIpCity.get(ip, api_key='free')
    #print(response1)
    m = folium.Map([response1.latitude, response1.longitude],
                   tiles='cartodbpositron',
                   zoom_start=5,
                   prefer_canvas=True)

    # Minimapa
    minimap = plugins.MiniMap(toggle_display=True)
    m.add_child(minimap)

    # add full screen button to map
    plugins.Fullscreen(position='topright').add_to(m)

    # Declaring points of latitude and longitude
    #my_locations = [(response1.latitude, response1.longitude),(-25.45,-49.34),(-25.45,-49.34)]
    doc_ref = db.collection('Pegasus').document(u'Exame')
    docs = doc_ref.get()
    exp = docs.to_dict()
    print(exp['Geopoints'][0])
    print(exp['Geopoints'][1])
    my_locations = [(exp['Geopoints'][0], exp['Geopoints'][1])]
    marker_cluster = MarkerCluster(my_locations)
    marker_cluster.add_to(m)

    #HeatMap(df).add_to(m)
    m.save('lab/templates/lab/mapa.html')

    table_file = open('lab/templates/lab/mapa.html')
    map_lines = table_file.readlines()
    table_file.close()

    table_file = open('lab/templates/lab/mapa.html', 'w+')
    first_lines = [
        "{% extends 'lab/base.html'%} \n",
        #"{% load static %} \n",
        "{% block content %} \n",
        "{% if user.is_authenticated %} \n"
    ]
    end_lines = ["\n{% endif %}\n", "{% endblock %}"]
    table_file.writelines(first_lines)
    table_file.writelines(map_lines)
    table_file.close()
    table_file = open('lab/templates/lab/mapa.html', 'a+')
    table_file.writelines(end_lines)
    table_file.close()

    return render(request, 'lab/mapa.html')
Exemple #9
0
def interactive_facilities_map(facilities_nm):
    facilities = gpd.read_file(facilities_nm)
    facilities = add_facilities_icon(facilities)
    
    map_center = get_map_center(facilities)
    maploc = folium.Map(location=map_center, zoom_start=6, prefer_canvas=True, tiles="Stamen Terrain")
    marker_cluster = MarkerCluster().add_to(maploc)

    facility_locations = facilities[['FacilityLatitude', 'FacilityLongitude']]
    fclty_pnts = facility_locations.values.tolist()

    for fc_pnt in range(0, len(fclty_pnts)):
        f = folium.Figure()

        # add campsite mini map into popup window (due to high load times, this feature was removed)
        # facility_id = facilities['FacilityID'][fc_pnt]
        # campsite_map = interactive_campsite_map(campsite_nm, facility_id)
        # campsite_map.add_to(f)

        facility_popup_info = f"___________________________________________________________________________________________ <br> \
                                            <b style='color:Tomato;'>Facility Name:</b> {facilities['FacilityName'][fc_pnt]} <br><br> \
                                                    <b style='color:Tomato;'>Facility ID:</b>  {facilities['FacilityID'][fc_pnt]} <br><br> \
                                                        <b style='color:Tomato;'>Facility Type:</b>  {facilities['FacilityTypeDescription'][fc_pnt]} <br><br> \
                                                            <b style='color:Tomato;'> Total Campsites:</b>  {facilities['TotalCampsites'][fc_pnt]} <br><br> \
                                                                <b style='color:Tomato;'>Reservable:</b> {facilities['Reservable'][fc_pnt]} <br><br> \
                                                                    {facilities['FacilityDescription'][fc_pnt]} <br><br>\
                                                                ___________________________________________________________________________________________ <br>"
        iframe = folium.IFrame(html=facility_popup_info, width=500, height=300)
        f.add_to(iframe)
        popup = folium.Popup(iframe, max_width=2650)

        facility_icon = folium.Icon(color = 'green')#icon= facilities['FacilityTypeIcon'][fc_pnt], icon='map-pin', prefix='fa')          
        folium.Marker(fclty_pnts[fc_pnt], popup= popup, icon = facility_icon, tooltip=facilities['FacilityName'][fc_pnt]).add_to(marker_cluster)
    
    plugins.Fullscreen(
        position="topright",
        title="Expand me",
        title_cancel="Exit me",
        force_separate_button=True,
    ).add_to(maploc)

    minimap = plugins.MiniMap()
    maploc.add_child(minimap)
    plugins.Geocoder().add_to(maploc)

    maploc.save("../docs/facility_map.html")
    return maploc
Exemple #10
0
 def make_map_and_marker(self):
     self.fileGPX = self.pathLbl["text"]
     self.fileHTML = self.htmlEnt.get()
     story = self
     self.storyTxt.delete(0.0, END)
     self.storyTxt.insert(0.0, story)
     pointsXY = self.points_xy()
     lat = float(sum(p[0] for p in pointsXY) / len(pointsXY))
     lon = float(sum(p[1] for p in pointsXY) / len(pointsXY))
     mapka = folium.Map(location=[lat, lon],
                        zoom_start=13,
                        control_scale=True)
     folium.PolyLine(pointsXY, color="blue", weight=3.5,
                     opacity=1).add_to(mapka)
     folium.CircleMarker(location=[lat, lon],
                         color='none',
                         radius=25,
                         fill_color='blue',
                         popup=self,
                         tooltip=self.fileGPX).add_to(mapka)
     folium.raster_layers.TileLayer('Open Street Map').add_to(mapka)
     folium.raster_layers.TileLayer('StamenTerrain').add_to(mapka)
     folium.raster_layers.TileLayer('CartoDB Positron').add_to(mapka)
     folium.raster_layers.TileLayer('StamenToner').add_to(mapka)
     folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(mapka)
     folium.raster_layers.TileLayer('Stamen Watercolor').add_to(mapka)
     folium.LayerControl().add_to(mapka)
     minimap = plugins.MiniMap(toggle_display=True)
     mapka.add_child(minimap)
     plugins.Fullscreen(position='topright').add_to(mapka)
     measureControl = plugins.MeasureControl(position='topleft',
                                             active_color='red',
                                             completed_color='red',
                                             primary_length_unit='km')
     mapka.add_child(measureControl)
     draw = plugins.Draw(position='topleft', export='True')
     draw.add_to(mapka)
     mapka.save(self.fileHTML)
     html_page = f'{self.fileHTML}'
     mapka.save(html_page)
     new = 2
     webbrowser.open(html_page, new=new)
     tkinter.messagebox.showinfo(
         "Analiza gpx", "Zakończono analizę pliku i dołączono mapę")
Exemple #11
0
def mymap(nodelst):
    pos = G.nodes[nodelst[0]]  # for the start point

    # creating the Map focusing on the start point

    vismap = folium.Map(location=[pos['latitude'], pos['longitude']],
                        zoom_start=10)

    #Layers Map

    folium.raster_layers.TileLayer('Open Street Map').add_to(vismap)
    folium.raster_layers.TileLayer('Stamen Terrain').add_to(vismap)

    #adding lcontrol on map
    folium.LayerControl().add_to(vismap)

    #minimap

    # plugin for mini map
    visminimap = plugins.MiniMap(toggle_display=True)

    # add minimap to map
    vismap.add_child(visminimap)

    # add scroll zoom toggler to map
    plugins.ScrollZoomToggler().add_to(vismap)

    # creating a marker of HOme on the start point

    folium.Marker(location=[(pos['latitude']), (pos['longitude'])],
                  icon=folium.Icon(color='red', icon='home'),
                  popup=(nodelst[0])).add_to(vismap)

    # creating a marker on the rest of the point

    for i in range(len(nodelst) - 1):
        pos = (G.nodes[nodelst[i + 1]])
        folium.Marker(location=[(pos['latitude']), (pos['longitude'])],
                      popup=(nodelst[i + 1])).add_to(vismap)

    return vismap
Exemple #12
0
def base_map_with_layers():
    """
    We can add layers to the map and they will be available in the map for selection.
    :return:
    """
    map_layer_control = folium.Map(location=[38, -98], zoom_start=4)

    folium.raster_layers.TileLayer('Open Street Map').add_to(map_layer_control)
    folium.raster_layers.TileLayer('Stamen Terrain').add_to(map_layer_control)
    folium.raster_layers.TileLayer('Stamen Toner').add_to(map_layer_control)
    folium.raster_layers.TileLayer('Stamen Watercolor').add_to(map_layer_control)
    folium.raster_layers.TileLayer('CartoDB Positron').add_to(map_layer_control)
    folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(map_layer_control)

    folium.LayerControl().add_to(map_layer_control)

    # Optional Minimap to bottom left corner
    minimap = plugins.MiniMap(toggle_display=True)
    map_layer_control.add_child(minimap)

    return map_layer_control
Exemple #13
0
    def map(nodelst):  #start point
        pos = G.nodes[nodelst[0]]
        vismap = folium.Map(location=[pos['latitude'], pos['longitude']],
                            zoom_start=10)
        folium.raster_layers.TileLayer('Open Street Map').add_to(vismap)
        folium.raster_layers.TileLayer('Stamen Terrain').add_to(vismap)
        folium.LayerControl().add_to(vismap)
        #minimap
        visminimap = plugins.MiniMap(toggle_display=True)
        #add to map
        vismap.add_child(visminimap)
        plugins.ScrollZoomToggler().add_to(vismap)
        folium.Marker(location=[(pos['latitude']), (pos['longitude'])],
                      icon=folium.Icon(color='red', icon='home'),
                      popup=(nodelst[0])).add_to(vismap)
        for i in range(len(nodelst) - 1):
            pos = (G.nodes[nodelst[i + 1]])
            folium.Marker(location=[(pos['latitude']), (pos['longitude'])],
                          popup=(nodelst[i + 1])).add_to(vismap)

        return vismap
def initmap():
    df = pd.read_csv('data/locations.csv', sep=',')
    df.head()

    df['Occupancy Percentage'] = pd.to_numeric(df['Occupancy Percentage'],
                                               errors='coerce')
    df['norm_occupancy'] = df['Occupancy Percentage'].apply(lambda x: x / 100)
    df = df.dropna()

    unique = df['datetime'].unique()

    list_data = []
    for timestamp in unique:
        tempdf = df.loc[df['datetime'] == timestamp]
        templist = [[row['latitude'], row['longitude'], row['norm_occupancy']]
                    for index, row in tempdf.iterrows()]
        list_data.append(templist)

    parking = folium.Map(location=[50.7260218, -1.8827525],
                         zoom_start=13,
                         tiles="stamentoner")
    hm = plugins.HeatMapWithTime(list_data,
                                 index=[date for date in unique],
                                 auto_play=False,
                                 radius=40,
                                 max_opacity=0.8)
    hm.layer_name = 'Heatmap'
    parking.add_child(hm)

    minimap = plugins.MiniMap()
    parking.add_child(minimap)

    json14 = os.path.join('data', 'carparkmap.json')

    #Load GeoJson

    folium.GeoJson(json14, name='geojson').add_to(parking)
    folium.LayerControl().add_to(parking)

    parking.save(outfile='templates/map.html')
Exemple #15
0
def add_minimap(map_name):
    # Plugin for mini map
    minimap = plugins.MiniMap(toggle_display = True)
    map_name.add_child(minimap) # Add minimap
    plugins.ScrollZoomToggler().add_to(map_name) # Add scroll zoom toggler to map
    plugins.Fullscreen(position='topright').add_to(map_name) # Add full screen button to map
Exemple #16
0
    def __init__(self, **kwargs):

        import logging

        logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR)

        if "ee_initialize" not in kwargs.keys():
            kwargs["ee_initialize"] = True

        if kwargs["ee_initialize"]:
            ee_initialize()

        # Default map center location and zoom level
        latlon = [40, -100]
        zoom = 4

        # Interchangeable parameters between ipyleaflet and folium
        if "center" in kwargs.keys():
            kwargs["location"] = kwargs["center"]
            kwargs.pop("center")
        if "location" in kwargs.keys():
            latlon = kwargs["location"]
        else:
            kwargs["location"] = latlon

        if "zoom" in kwargs.keys():
            kwargs["zoom_start"] = kwargs["zoom"]
            kwargs.pop("zoom")
        if "zoom_start" in kwargs.keys():
            zoom = kwargs["zoom_start"]
        else:
            kwargs["zoom_start"] = zoom

        if "add_google_map" not in kwargs.keys() and "basemap" not in kwargs.keys():
            kwargs["add_google_map"] = True
        if "plugin_LatLngPopup" not in kwargs.keys():
            kwargs["plugin_LatLngPopup"] = True
        if "plugin_Fullscreen" not in kwargs.keys():
            kwargs["plugin_Fullscreen"] = True
        if "plugin_Draw" not in kwargs.keys():
            kwargs["plugin_Draw"] = False
        if "Draw_export" not in kwargs.keys():
            kwargs["Draw_export"] = True
        if "plugin_MiniMap" not in kwargs.keys():
            kwargs["plugin_MiniMap"] = False
        if "plugin_LayerControl" not in kwargs.keys():
            kwargs["plugin_LayerControl"] = False

        super().__init__(**kwargs)
        self.baseclass = "folium"

        if kwargs.get("add_google_map"):
            ee_basemaps["ROADMAP"].add_to(self)
        if kwargs.get("basemap"):
            ee_basemaps[kwargs.get("basemap")].add_to(self)
        if kwargs.get("plugin_LatLngPopup"):
            folium.LatLngPopup().add_to(self)
        if kwargs.get("plugin_Fullscreen"):
            plugins.Fullscreen().add_to(self)
        if kwargs.get("plugin_Draw"):
            plugins.Draw(export=kwargs.get("Draw_export")).add_to(self)
        if kwargs.get("plugin_MiniMap"):
            plugins.MiniMap().add_to(self)
        if kwargs.get("plugin_LayerControl"):
            folium.LayerControl().add_to(self)

        self.fit_bounds([latlon, latlon], max_zoom=zoom)
def add_minimap(map_name):
  
    minimap = plugins.MiniMap(toggle_display = True)
    map_name.add_child(minimap) 
    plugins.ScrollZoomToggler().add_to(map_name) 
    plugins.Fullscreen(position='topright').add_to(map_name) 
Exemple #18
0
def create_markup_map(name: str, df: pd.core.frame.DataFrame):
    """Place a markup for each point with a valid
    housing price evaluation and position
    """
    map_ = folium.Map(
        location=france_location,
        zoom_start=3,
        control_scale=True,
        tiles="openstreetmap",
    )
    mcg = folium.plugins.MarkerCluster(control=False)
    map_.add_child(mcg)

    houses = folium.plugins.FeatureGroupSubGroup(mcg, "houses")
    appartements = folium.plugins.FeatureGroupSubGroup(mcg, "appartements")
    others = folium.plugins.FeatureGroupSubGroup(mcg, "others")
    map_.add_child(houses)
    map_.add_child(appartements)
    map_.add_child(others)

    for _, row in df.iterrows():
        housing_type = row["Type local"]
        if housing_type == "Maison":
            color = "darkgreen"
            icon = "home"
            context = houses

        elif housing_type == "Appartement":
            color = "red"
            icon = "pause"
            context = appartements
        else:
            color = "black"
            icon = "info-sign"
            context = others

        price = int(row["Valeur fonciere"])
        address = get_address_from_row(row)
        context.add_child(
            folium.Marker(
                (row["lat"], row["lon"]),
                popup=folium.Popup(
                    f"{housing_type}</br> {address} <b>{price}€</b>",
                    # Not working properly
                    max_width="400px",
                    min_width="200px",
                ),
                tooltip=housing_type,
                icon=folium.Icon(color=color, icon=icon),
            )
        )

    map_.add_child(
        plugins.Fullscreen(
            position="topright",
            title="Expand me",
            title_cancel="Exit me",
            force_separate_button=True,
        )
    )
    map_.add_child(folium.LayerControl(collapsed=False))
    map_.add_child(plugins.MeasureControl())
    map_.add_child(plugins.MiniMap())
    save_map(map_, name)
def makemap(lst):

    geomap = folium.Map([23.75, 121], zoom_start=8, tiles="cartodbpositron")
    folium.TileLayer('stamenterrain').add_to(geomap)
    folium.TileLayer('openstreetmap').add_to(geomap)

    colors = ["#FFFFFF", "#FFAAAA", "#FF6666","#FF6666", "#FF6666","#FF6666",
              "#FF0000","#FF0000","#FF0000","#FF0000"] 
    cm     = branca.colormap.LinearColormap(colors, vmin=0, vmax=1).to_step(len(colors))
    cm.caption = 'EI value'
    geomap.add_child(cm)
    sp,*pred = lst
    dfsp = pd.read_csv("../output_csv/combine/{}.csv".format(sp))
    tl1 = get_list(dfsp,2)
    if len(pred) == 1:
        pred1 = pd.read_csv("../output_csv/combine/{}.csv".format(pred[0]))
        tl2 =  get_list(pred1,1,ref=True)
        tl3 = []
    elif len(pred) == 2:
        pred1 = pd.read_csv("../output_csv/combine/{}.csv".format(pred[0]))
        pred2 = pd.read_csv("../output_csv/combine/{}.csv".format(pred[1]))
        tl2 =  get_list(pred1,1,ref=True)
        tl3 =  get_list(pred2,3,ref=True)
    else:
        tl2 = tl3 = []
    features = add_station(dfsp,sp)
    FC = tl1 + tl2 + tl3 + features
    plugins.TimestampedGeoJson(
        {
            'type': 'Feature',
            'features': FC

        },
        period='P1M',
        duration='P15D',
        auto_play=False,
        loop=False,
        loop_button=True,
        date_options='YYYY/MM',
    ).add_to(geomap)


    plugins.Fullscreen(position='topright', force_separate_button=True).add_to(geomap)
    plugins.MiniMap().add_to(geomap)
    plugins.MeasureControl(primary_length_unit='kilometers', 
                         secondary_length_unit='meters', 
                         primary_area_unit='hectares', 
                         secondary_area_unit='sqmeters').add_to(geomap)
    formatter = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};"

    plugins.MousePosition(
        position='bottomleft',
        separator=' | ',
        empty_string='NaN',
        lng_first=True,
        num_digits=20,
        prefix='Coordinates:',
        lat_formatter=formatter,
        lng_formatter=formatter
    ).add_to(geomap)
    geomap.add_child(folium.LayerControl(position="topleft"))
#    return geomap
    geomap.save('../html/{}.html'.format(sp))
Exemple #20
0
def carte(df):
    ###############################################################################
    ############........ CARTE DES MARCHES PAR VILLE
    df_carte = df[[
        'latitudeAcheteur', 'longitudeAcheteur', 'libelleCommuneAcheteur'
    ]]
    df_carte = df_carte[df_carte['latitudeAcheteur'] != 'nan']
    df_carte = df_carte[df_carte['longitudeAcheteur'] != 'nan']
    df_carte = df_carte.drop_duplicates(
        subset=['latitudeAcheteur', 'longitudeAcheteur'], keep='first')
    df_carte.reset_index(inplace=True, drop=True)

    dfMT = df.groupby(['latitudeAcheteur', 'longitudeAcheteur'
                       ]).montant.sum().to_frame('montantTotal').reset_index()
    dfMM = df.groupby([
        'latitudeAcheteur', 'longitudeAcheteur'
    ]).montant.mean().to_frame('montantMoyen').reset_index()
    dfIN = df.groupby([
        'latitudeAcheteur', 'longitudeAcheteur'
    ]).identifiantMarche.nunique().to_frame('nbMarches').reset_index()
    dfSN = df.groupby([
        'latitudeAcheteur', 'longitudeAcheteur'
    ]).siretEtablissement.nunique().to_frame('nbEntreprises').reset_index()
    dfDM = df.groupby(['latitudeAcheteur', 'longitudeAcheteur'
                       ]).distanceAcheteurEtablissement.median().to_frame(
                           'distanceMediane').reset_index()

    df_carte = pd.merge(df_carte,
                        dfMT,
                        how='left',
                        on=['latitudeAcheteur', 'longitudeAcheteur'])
    df_carte = pd.merge(df_carte,
                        dfMM,
                        how='left',
                        on=['latitudeAcheteur', 'longitudeAcheteur'])
    df_carte = pd.merge(df_carte,
                        dfIN,
                        how='left',
                        on=['latitudeAcheteur', 'longitudeAcheteur'])
    df_carte = pd.merge(df_carte,
                        dfSN,
                        how='left',
                        on=['latitudeAcheteur', 'longitudeAcheteur'])
    df_carte = pd.merge(df_carte,
                        dfDM,
                        how='left',
                        on=['latitudeAcheteur', 'longitudeAcheteur'])
    df_carte = pd.merge(df_carte,
                        df,
                        how='left',
                        on=['libelleCommuneAcheteur'])

    df_carte.montantTotal = round(df_carte.montantTotal, 0)
    df_carte.montantMoyen = round(df_carte.montantMoyen, 0)
    df_carte.nbMarches = round(df_carte.nbMarches, 0)
    df_carte.nbEntreprises = round(df_carte.nbEntreprises, 0)
    df_carte.distanceMediane = round(df_carte.distanceMediane, 0)
    df_carte.distanceMediane = np.where(df_carte.distanceMediane.isnull(), 0,
                                        df_carte.distanceMediane)

    ###############################################################################
    ### Carte des DECP
    geojson = json.loads(
        urllib.request.urlopen(
            'https://france-geojson.gregoiredavid.fr/repo/regions.geojson').
        read())
    df_Reg = df.groupby([
        'codeRegionAcheteur'
    ]).montant.sum().to_frame('montantMoyen').reset_index()
    df_Reg.columns = ['code', 'montant']
    df_Reg = df_Reg[(df_Reg.code != 'nan') & (df_Reg.code != '98')]
    df_Reg.montant = round(df_Reg.montant / 1000000, 0).astype(int)
    df_Reg.montant = np.where(df_Reg.montant > 10000, 10000, df_Reg.montant)

    path = os.path.join(path_to_data, conf["departements-francais"])
    depPop = pd.read_csv(path,
                         sep='\t',
                         encoding='utf-8',
                         usecols=['NUMÉRO', 'POPULATION'])
    depPop.columns = ['code', 'population']
    depPop.code = depPop.code.astype(str)
    depPop = depPop[depPop.population.notnull()]
    depPop.population = depPop.population.astype(int)
    for i in range(len(depPop)):
        if len(depPop['code'][i]) < 2:
            depPop['code'][i] = '0' + depPop['code'][i]

    geojson2 = json.loads(
        urllib.request.urlopen(
            'https://raw.githubusercontent.com/gregoiredavid/france-geojson/master/departements-avec-outre-mer.geojson'
        ).read())
    df_Dep = df.groupby([
        'codeDepartementAcheteur'
    ]).montant.sum().to_frame('montantMoyen').reset_index()
    df_Dep.columns = ['code', 'montant']
    df_Dep = df_Dep[(df_Dep.code != 'nan')]
    df_Dep = pd.merge(df_Dep, depPop, how='left', on='code')
    df_Dep = df_Dep[df_Dep.population.notnull()]
    df_Dep.montant = round(df_Dep.montant / df_Dep.population, 0).astype(int)
    df_Dep.montant = np.where(df_Dep.montant > 2000, 2000, df_Dep.montant)

    dfHM = df[['latitudeAcheteur', 'longitudeAcheteur']]
    dfHM = dfHM[(dfHM.latitudeAcheteur != 'nan') |
                (dfHM.longitudeAcheteur != 'nan')]

    ### Mise en forme
    c = folium.Map(location=[47, 2.0], zoom_start=6, control_scale=True)
    plugins.MiniMap(toggle_display=True).add_to(c)

    mapMarker = folium.Marker(
        [44, -4],
        icon=folium.features.CustomIcon(
            'https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/1000px-Information_icon.svg.png',
            icon_size=(20, 20)),
        popup=folium.Popup(
            '<b>Indicateur de distance</b></br></br>' +
            '<img src="https://icon-library.com/images/map-pin-icon/map-pin-icon-17.jpg"  width=8 height=8/>'
            + ' ' +
            '<img src="https://icon-library.com/images/map-pin-icon/map-pin-icon-17.jpg"  width=14 height=14/>'
            + ' ' +
            '<img src="https://icon-library.com/images/map-pin-icon/map-pin-icon-17.jpg"  width=20 height=20/> : Distance moyenne</br>entre acheteurs et entreprises'
            + '</br></br>' + '<b>Ségmentation des acheteurs </b></br></br>' +
            '<img src="https://icon-library.com/images/map-pin-icon/map-pin-icon-17.jpg"  width=20 height=20/> : Petit'
            + '</br>' +
            '<img src="https://cdn1.iconfinder.com/data/icons/vibrancie-map/30/map_001-location-pin-marker-place-512.png"  width=20 height=20/> : Moyen'
            + '</br>' +
            '<img src="https://cdn.cnt-tech.io/api/v1/tenants/dd1f88aa-e3e2-450c-9fa9-a03ea59a6bf0/domains/57a9d53a-fe30-4b6f-a4de-d624bd25134b/buckets/8f139e2f-9e74-4be3-9d30-d8f180f02fbb/statics/56/56d48498-d2bf-45f8-846e-6c9869919ced"  width=20 height=20/> : Grand'
            + '</br>' +
            '<img src="https://svgsilh.com/svg/157354.svg"  width=20 height=20/> : Hors-segmentation',
            max_width=320,
            show=True),
        overlay=False).add_to(c)

    marker_cluster = MarkerCluster(name='DECP par communes').add_to(c)
    for i in range(len(df_carte)):
        if (df_carte.segmentation_CAH[i] == 1):
            icon = folium.features.CustomIcon(
                'https://icon-library.com/images/map-pin-icon/map-pin-icon-17.jpg',
                icon_size=(max(20, min(40, df_carte.distanceMediane[i] / 2)),
                           max(20, min(40, df_carte.distanceMediane[i] / 2))))
        elif (df_carte.segmentation_CAH[i] == 2):
            icon = folium.features.CustomIcon(
                'https://cdn1.iconfinder.com/data/icons/vibrancie-map/30/map_001-location-pin-marker-place-512.png',
                icon_size=(max(20, min(40, df_carte.distanceMediane[i] / 2)),
                           max(20, min(40, df_carte.distanceMediane[i] / 2))))
        elif (df_carte.segmentation_CAH[i] == 3):
            icon = folium.features.CustomIcon(
                'https://cdn.cnt-tech.io/api/v1/tenants/dd1f88aa-e3e2-450c-9fa9-a03ea59a6bf0/domains/57a9d53a-fe30-4b6f-a4de-d624bd25134b/buckets/8f139e2f-9e74-4be3-9d30-d8f180f02fbb/statics/56/56d48498-d2bf-45f8-846e-6c9869919ced',
                icon_size=(max(20, min(40, df_carte.distanceMediane[i] / 2)),
                           max(20, min(40, df_carte.distanceMediane[i] / 2))))
        else:
            icon = folium.features.CustomIcon(
                'https://svgsilh.com/svg/157354.svg',
                icon_size=(max(20, min(40, df_carte.distanceMediane[i] / 2)),
                           max(20, min(40, df_carte.distanceMediane[i] / 2))))

        folium.Marker(
            [df_carte.latitudeAcheteur[i], df_carte.longitudeAcheteur[i]],
            icon=icon,
            popup=folium.Popup(
                '<b><center>' + df_carte.libelleCommuneAcheteur[i] +
                '</center></b></br>' + '<b>' +
                df_carte.nbMarches[i].astype(str) + '</b> marchés ' +
                'pour un montant moyen de <b>' +
                round(df_carte.montantMoyen[i] / 1000,
                      0).astype(int).astype(str) + ' mille euros</b> ' +
                "</br>avec <b>" + df_carte.nbEntreprises[i].astype(str) +
                ' entreprises</b> ' + "à une distance médiane de <b>" +
                df_carte.distanceMediane[i].astype(int).astype(str) +
                ' km</b> ',
                max_width=320,
                min_width=200),
            tooltip=folium.Tooltip(df_carte.libelleCommuneAcheteur[i]),
            clustered_marker=True).add_to(marker_cluster)

    HeatMap(data=dfHM[['latitudeAcheteur', 'longitudeAcheteur']],
            radius=10,
            name="HeatMap des marchés",
            show=False,
            overlay=False).add_to(c)

    choropleth = folium.Choropleth(
        geo_data=geojson,
        name='Régions',
        data=df_Reg,
        columns=['code', 'montant'],
        key_on='feature.properties.code',
        fill_color='YlGnBu',
        fill_opacity=0.7,
        line_opacity=0.2,
        nan_fill_color='#8c8c8c',
        highlight=True,
        line_color='black',
        show=False,
        overlay=False,
        legend_name="Montant total des marchés (en millions €)").add_to(c)
    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(['nom'], labels=False))

    choropleth = folium.Choropleth(
        geo_data=geojson2,
        name='Départements',
        data=df_Dep,
        columns=['code', 'montant'],
        key_on='feature.properties.code',
        fill_color='YlOrRd',
        fill_opacity=0.7,
        line_opacity=0.2,
        nan_fill_color='#8c8c8c',
        highlight=False,
        line_color='black',
        show=False,
        overlay=False,
        legend_name="Montant total par habitants (en milliers €)").add_to(c)
    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(['nom'], labels=False))

    folium.TileLayer('OpenStreetMap', overlay=True, show=True,
                     control=False).add_to(c)
    folium.LayerControl(collapsed=False).add_to(c)
    c.save('carte/carteDECP.html')
Exemple #21
0
def create_map():

    get_countries()
    get_cities()

    global translator, update_time, cities, db, city_update_time

    # Number of Total Cases in all around the world
    total_cases = data[1:].TotalCases.sum()
    total_deaths = data[1:].TotalDeaths.sum()

    # Empty Folium Map with that uses Open Street Map as a tile
    m = folium.Map(location=[39.933333333333,32.866667], tiles='OpenStreetMap', zoom_start=5)

    # Title of map
    title = "<div class='container'><h1 class='text-center'>CoronaVirus (Covid-19) Haritası</h1><center>Güncelleme Zamanı: {t1}, İl Verileri {t2} Tarihine Aittir</center></div>".format(t1=update_time, t2="03.04.2020")
    # m.get_root().html.add_child(folium.Element(title))

    # CSV file for marking each country on its capitals. This file contains countries information which are name and coordinates of capitals and region of country
    capitals = pd.read_csv('countries.csv')

    print("Number of countries", data.shape[0])

    # Minimum radius for marking countries with circle
    min_radius = 50000

    cursor = db.cursor()
    il_feature_group = folium.FeatureGroup(name='İl Verisi')
    ulke_feature_group = folium.FeatureGroup(name="Ülke Verisi", show=False)

    update_time_query = 'update update_time set all_data="{v1}", cities_data="{v2}" where row = 1'.format(
        v1=update_time, v2=city_update_time
    )
    cursor.execute(update_time_query)
    db.commit()

    api_check = False
    try:
        translator.translate("API Control", src="en", dest="tr").text
    except json.decoder.JSONDecodeError:
        print("googletrans json error")
        api_check = False
    else:
        api_check = True

    # For every country in countries array on global, loop draw circle with respect to number of total cases in country
    for country in countries[1:]:

        temp = capitals[capitals.CountryName == country.name]
        print("CountryName: ", country.name)
        temp = temp.reset_index()
        print(temp.iloc[0].CapitalName)

        # print("Total Cases: ", total_cases)
        print("Case:", country.total_cases)
        radius = (int(country.total_cases) / int(total_cases)) * 2000000
        radius += min_radius
        print("Radius:", radius)

        country_name = temp.iloc[0].ActualName

        if api_check:
            try:
                country_name = translator.translate(temp.iloc[0].ActualName, src="en", dest="tr").text
            except json.decoder.JSONDecodeError:
                print("googletrans json error")

        text = "<div><h4>" + country_name + "</h4><h5>Vaka Sayısı: " + str(
            int(country.total_cases)) + "</h5><h5>Ölü Sayısı: " + str(int(country.total_deaths)) + "</h5></div>"
        popup = folium.Popup(html=text, max_width=200, min_width=150, sticky=False)
        tooltip = folium.Tooltip(text=country_name)
        country_Circle = folium.Circle(
            location=(temp.iloc[0].CapitalLatitude, temp.iloc[0].CapitalLongitude),
            popup=popup,
            radius=(radius if radius > min_radius else min_radius),
            color='red',
            fill=True,
            fill_color='red',
            tooltip=tooltip
        )

        if country.name == "Turkey":
            for city in cities:

                # folium.Polygon(city.coordinates).add_to(m)
                city_geojson = create_geojson(city, country)
                percentage = (city.total_cases/country.total_cases)*100
                print("Percentage: ", percentage)
                style_function = lambda feature: {'fillColor': 'red', 'fillOpacity': 0.15 + (int(feature['properties']['total_cases'])/int(feature['properties']['country_total_cases'])), 'color': 'white', 'weight': 0.75}
                text = "<div><h5>" + city.name + "</h5><h6>Vaka Sayısı: " + str(int(city.total_cases)) \
                       + " (%{:.2f}) ".format(percentage)\
                       + "</h6><h6>Ölü Sayısı: " + str(int(city.total_deaths)) + "</h6><hr><h4>" + str(country.name)\
                       + "</h4><h5>Vaka Sayısı: " + str(int(country.total_cases)) + "</h5>" \
                       + "<h5>Ölü Sayısı: " + str(int(country.total_deaths)) + "</h5></div>"
                popup = folium.Popup(html=text, max_width=200, min_width=150, sticky=False)
                tooltip = folium.Tooltip(text=city.name)
                geoJsonLayer = folium.GeoJson(city_geojson, style_function=style_function, tooltip=tooltip)
                geoJsonLayer.add_child(popup)
                geoJsonLayer.add_to(il_feature_group)

                country_Circle.add_to(ulke_feature_group)
        else:
           country_Circle.add_to(m)

    item_txt = """<br> &nbsp; Vaka Sayısı: &nbsp; {total_cases} <br> &nbsp; Ölü Sayısı:  &nbsp; {total_deaths}"""
    html_itms = item_txt.format(total_cases=int(total_cases), total_deaths=int(total_deaths))

    legend_html = """
         <div style="
         position: fixed; 
         bottom: 25px; left: 25px;
         border:2px white; z-index:9999; 

         font-size:12px;
         font-weight: bold;
         background: white;
         color: #5f6769;
         opacity: 0.8;
         padding : 5px;
         ">
         <center><h5>{title}</h5></center>

         {itm_txt}

          </div> """.format(title="Dünya Geneli", itm_txt=html_itms)
    m.get_root().html.add_child(folium.Element(legend_html))

    il_feature_group.add_to(m)
    ulke_feature_group.add_to(m)
    folium.LayerControl(collapsed=True).add_to(m)

    minimap = plugins.MiniMap(width=100, height=75, minimized=True, toggle_display=True)
    m.add_child(minimap)

    m.save(map_path)

    print("You can find map file at: ", os.path.join(os.getcwd(), map_path))
                  popup=parque['NOMBRE_PARQUE'],
                  tooltip=parque['NOMBRE_PARQUE']).add_to(mapa_parques)
    elif parque['TIPOLOGIA'] == 'Parque lineal':
        fl.Marker(location=(parque['LAT'], parque['LONG']),
                  icon=fl.Icon(color="pink", icon_color="#D81159"),
                  popup=parque['NOMBRE_PARQUE'],
                  tooltip=parque['NOMBRE_PARQUE']).add_to(mapa_parques)
    else:
        fl.Marker(location=(parque['LAT'], parque['LONG']),
                  icon=fl.Icon(color="lightgreen", icon_color='#70B77E'),
                  popup=parque['NOMBRE_PARQUE'],
                  tooltip=parque['NOMBRE_PARQUE']).add_to(mapa_parques)

# Display
mini_map = plugins.MiniMap(toggle_display=True,
                           width=200,
                           height=200,
                           collapsed_width=25)
mapa_parques.add_child(mini_map)

mapa_parques

# In[120]:

### GUARDARLO COMO HTML
mapa_parques.save(outfile="MAPA_OVERVIEW.html")

# In[83]:

df_urbano = pd.read_csv(
    'https://raw.githubusercontent.com/MakiChavez/areas_verdes/main/Urbano.csv'
)
Exemple #23
0
def make_map() -> None:
    """
    Generate a map of US with forest fires from years 2010 to 2015.
    """
    # Extracting the data using the function above
    fire_data = read_file_map('FireData5yrs.csv')

    # Creating a data frame
    container = pd.DataFrame({
        'lon': fire_data['Longitude'],
        'lat': fire_data['Latitude'],
        'Size': fire_data['Fire Size'],
        'Veg': fire_data["Vegetation"],
        'FMag': fire_data["Fire Magnitude"],
        'Wind': fire_data['Wind Contained'],
        'Humid': fire_data['Humid Contained'],
        'remote': fire_data['Remoteness'],
        'link': fire_data['Links'],
        'time': fire_data['Time']
    })

    # Creates the Map
    m = folium.Map(location=[39.525501, -102.163384],
                   zoom_start=3,
                   prefer_canvas=True,
                   tiles='Stamen Terrain')

    # Overlay of the US
    outline_us = os.path.join('overlay.json')

    # Creating a Marker Cluster
    cluster = folium.plugins.MarkerCluster(name="Markers").add_to(m)

    heatmap = pd.read_csv('FireData5yrs.csv')

    # Adding a heat map:
    folium.Choropleth(geo_data=outline_us,
                      data=heatmap,
                      columns=['state', 'Vegetation'],
                      name='Fire Magnitude',
                      key_on='feature.id',
                      fill_color='YlGn',
                      fill_opacity=0.5,
                      line_opacity=0.5,
                      legend_name='Fire Magnitude',
                      highlight=True).add_to(m)

    folium.Choropleth(geo_data=outline_us,
                      data=heatmap,
                      columns=['state', "fire_mag"],
                      name='Vegetation',
                      key_on='feature.id',
                      fill_color='RdPu',
                      fill_opacity=0.5,
                      line_opacity=0.5,
                      legend_name='Vegetation',
                      highlight=True).add_to(m)

    folium.Choropleth(geo_data=outline_us,
                      data=heatmap,
                      columns=['state', "Hum_cont"],
                      name='Humidity',
                      key_on='feature.id',
                      fill_color='YlOrRd',
                      fill_opacity=0.5,
                      line_opacity=0.5,
                      legend_name='Humidity',
                      highlight=True).add_to(m)

    folium.Choropleth(geo_data=outline_us,
                      data=heatmap,
                      columns=['state', "Wind_cont"],
                      name='Wind',
                      key_on='feature.id',
                      fill_color='PuBuGn',
                      fill_opacity=0.5,
                      line_opacity=0.5,
                      legend_name='Wind',
                      highlight=True).add_to(m)

    # Iterating through the data and at each iteration adding its value.
    # It creates the marker and the popup with these information inside the popup.
    for i in range(0, len(container)):
        info_size = '<strong> Fire Size </strong>:' + container.iloc[i][
            'Size'] + 'g/mi'
        info_veg = '<strong> Vegetation </strong>:' + container.iloc[i]['Veg']
        info_mag = '<strong> Fire Magnitude </strong>:' + container.iloc[i][
            'FMag']
        info_wind = '<strong> Wind Contained </strong>:' + container.iloc[i][
            'Wind']
        info_humid = '<strong> Humidity Contained </strong>:' + container.iloc[
            i]['Humid']
        info_remote = '<strong> Remoteness </strong>:' + container.iloc[i][
            'remote']
        info_link = container.iloc[i]['link']
        info_time = '<strong> Year </strong>:' + container.iloc[i]['time']
        info_all = info_mag + '<br>' + info_time + '<br>' + info_veg + '<br>' + info_wind + '<br>' + \
                   info_humid + '<br>' + info_remote + '<br>' + info_size + '<br>' + \
                   '<a href=' + info_link + ' > [More Details] </ a >'
        (folium.Marker([container.iloc[i]['lat'], container.iloc[i]['lon']],
                       popup=folium.Popup(info_all,
                                          max_width=280,
                                          min_width=280),
                       icon=folium.Icon(color='red',
                                        icon='fa-fire',
                                        prefix='fa'),
                       tooltip='Click For More Information').add_to(cluster))

    # Add the outline to map
    folium.GeoJson(outline_us, name='America').add_to(m)

    # Adding a Mini Map
    mini = plugins.MiniMap(toggle_display=True)
    m.add_child(mini)

    # plugins.ScrollZoomToggler().add_to(m)
    plugins.Fullscreen(position='topright').add_to(m)

    # Adding More types of maps
    folium.TileLayer('OpenStreetMap').add_to(m)
    folium.TileLayer('Stamen Watercolor').add_to(m)
    folium.TileLayer('Stamen Terrain').add_to(m)
    folium.TileLayer('CartoDB positron').add_to(m)
    folium.TileLayer('CartoDB dark_matter').add_to(m)
    folium.LayerControl().add_to(m)

    # Saves the Map
    m.save('m.html')

    # Opens the Webpage
    webbrowser.open('m.html')
Exemple #24
0
    def map_html(self, tiltakspunkter, filepath):
        """
        tiltakspunkter er av typen Point og oppgitt i epsg:4326
        filepath er der du ønsker .html filen med kart skal havne.
        """

        tiltakspunkter = tiltakspunkter

        box_tmp = bounding_box(tiltakspunkter)
        box_center_x = (box_tmp[0] + box_tmp[2]) / 2
        box_center_y = (box_tmp[1] + box_tmp[3]) / 2

        map_center_lon = box_center_x
        map_center_lat = box_center_y

        map = folium.Map(location=[map_center_lat, map_center_lon],
                         zoom_start=9,
                         tiles='Stamen Terrain')

        tiltaksFeature = FeatureGroup(name='Tiltakspunkter', show=False)

        marker_cluster = plugins.MarkerCluster(options=dict(
            zoomToBoundsOnClick=False)).add_to(tiltaksFeature)

        #feature_tiltak = FeatureGroup(name='tiltakspunkter')
        tooltip_tiltak = 'Tiltakspunkt'

        tmp_tiltak = tiltakspunkter['punkt_geom_wkt']
        x_list = tmp_tiltak.apply(lambda p: p.x)
        y_list = tmp_tiltak.apply(lambda p: p.y)
        for i in range(0, len(x_list)):
            try:
                Marker(location=[y_list[i], x_list[i]],
                       popup=tiltakspunkter['punkt_navn'][i],
                       icon=folium.Icon(color='red',
                                        icon_color='black',
                                        icon='angle-double-down',
                                        prefix='fa'),
                       tooltip=tooltip_tiltak).add_to(marker_cluster)
            except:
                Marker(location=[y_list[i], x_list[i]],
                       popup='Atter et punkt',
                       icon=folium.Icon(color='red',
                                        icon_color='black',
                                        icon='angle-double-down',
                                        prefix='fa'),
                       tooltip=tooltip_tiltak).add_to(marker_cluster)

        feature_skipshaler = FeatureGroup(name='skipshaler')

        try:
            oljetankskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'oljetankskip')

            haler_feat_10 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 10]
            skipshaler_10_json = haler_feat_10.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#4DB6AC',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_olje = folium.features.GeoJson(
                skipshaler_10_json, style_function=style_skipshaler)
            haler_olje.add_to(oljetankskip)
        except:
            pass

        try:
            kjemikalie_produkttankskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'kjemikalie_produkttankskip')

            haler_feat_11 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 11]
            skipshaler_11_json = haler_feat_11.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#26A69A',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_kjemi = folium.features.GeoJson(
                skipshaler_11_json, style_function=style_skipshaler)
            haler_kjemi.add_to(kjemikalie_produkttankskip)
        except:
            pass

        try:
            gasstankskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'gasstankskip')

            haler_feat_12 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 12]
            skipshaler_12_json = haler_feat_12.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#009688',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_gass = folium.features.GeoJson(
                skipshaler_12_json, style_function=style_skipshaler)
            haler_gass.add_to(gasstankskip)
        except:
            pass

        try:
            bulkskip = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                    'bulkskip')

            haler_feat_13 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 13]
            skipshaler_13_json = haler_feat_13.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00897B',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_bulk = folium.features.GeoJson(
                skipshaler_13_json, style_function=style_skipshaler)
            haler_bulk.add_to(bulkskip)
        except:
            pass

        try:
            stykkgods_roro_skip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'stykkgods_roro_skip')

            haler_feat_14 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 14]
            skipshaler_14_json = haler_feat_14.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00796B',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_stykkgods = folium.features.GeoJson(
                skipshaler_14_json, style_function=style_skipshaler)
            haler_stykkgods.add_to(stykkgods_roro_skip)
        except:
            pass

        try:
            konteinerskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'konteinerskip')

            haler_feat_15 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 15]
            skipshaler_15_json = haler_feat_15.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00695C',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_konteiner = folium.features.GeoJson(
                skipshaler_15_json, style_function=style_skipshaler)
            haler_konteiner.add_to(konteinerskip)
        except:
            pass

        try:
            passasjerbat = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'passasjerbat')

            haler_feat_16 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 16]
            skipshaler_16_json = haler_feat_16.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#81C784',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_passasjer = folium.features.GeoJson(
                skipshaler_16_json, style_function=style_skipshaler)
            haler_passasjer.add_to(passasjerbat)
        except:
            pass

        try:
            ropax_skip = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                      'ropax_skip')

            haler_feat_17 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 17]
            skipshaler_17_json = haler_feat_17.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#66BB6A',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_ropax = folium.features.GeoJson(
                skipshaler_17_json, style_function=style_skipshaler)
            haler_ropax.add_to(ropax_skip)
        except:
            pass

        try:
            cruiseskip = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                      'cruiseskip')

            haler_feat_18 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 18]
            skipshaler_18_json = haler_feat_18.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#4CAF50',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_cruise = folium.features.GeoJson(
                skipshaler_18_json, style_function=style_skipshaler)
            haler_cruise.add_to(cruiseskip)
        except:
            pass

        try:
            offshore_supplyskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'offshore_supplyskip')

            haler_feat_19 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 19]
            skipshaler_19_json = haler_feat_19.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#43A047',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_offshore = folium.features.GeoJson(
                skipshaler_19_json, style_function=style_skipshaler)
            haler_offshore.add_to(offshore_supplyskip)
        except:
            pass

        try:
            andre_offshorefartoy = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'andre_offshorefartoy')

            haler_feat_20 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 20]
            skipshaler_20_json = haler_feat_20.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#388E3C',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_andre_offshore = folium.features.GeoJson(
                skipshaler_20_json, style_function=style_skipshaler)
            haler_andre_offshore.add_to(andre_offshorefartoy)
        except:
            pass

        try:
            bronnbat = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                    'bronnbat')

            haler_feat_21 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 21]
            skipshaler_21_json = haler_feat_21.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00E676',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_bronn = folium.features.GeoJson(
                skipshaler_21_json, style_function=style_skipshaler)
            haler_bronn.add_to(bronnbat)
        except:
            pass

        try:
            slepefartoy = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                       'slepefartoy')

            haler_feat_22 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 22]
            skipshaler_22_json = haler_feat_22.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00C853',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_slepe = folium.features.GeoJson(
                skipshaler_22_json, style_function=style_skipshaler)
            haler_slepe.add_to(slepefartoy)
        except:
            pass

        try:
            andre_servicefartoy = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'andre_servicefartoy')

            haler_feat_23 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 23]
            skipshaler_23_json = haler_feat_23.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#9CCC65',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_andre_service = folium.features.GeoJson(
                skipshaler_23_json, style_function=style_skipshaler)
            haler_andre_service.add_to(andre_servicefartoy)
        except:
            pass

        try:
            fiskefartoy = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                       'fiskefartoy')

            haler_feat_24 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 24]
            skipshaler_24_json = haler_feat_24.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#7CB342',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_fisk = folium.features.GeoJson(
                skipshaler_24_json, style_function=style_skipshaler)
            haler_fisk.add_to(fiskefartoy)
        except:
            pass

        try:
            annet = plugins.FeatureGroupSubGroup(feature_skipshaler, 'annet')

            haler_feat_25 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 25]
            skipshaler_25_json = haler_feat_25.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#558B2F',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_annet = folium.features.GeoJson(
                skipshaler_25_json, style_function=style_skipshaler)
            haler_annet.add_to(annet)
        except:
            pass

        feature_passlines = FeatureGroup(name='passeringslinjer')
        passeringslinje_json = self.passline.to_json(default=str)
        tooltip_passeringslinje = 'Passeringslinje'
        style_passline = lambda x: {
            'color': '#000000',
            'weight': 4,
            'opacity': 1.0,
        }
        folium.features.GeoJson(
            passeringslinje_json,
            style_function=style_passline,
            tooltip=tooltip_passeringslinje).add_to(feature_passlines)

        #feature_tiltak.add_to(marker_cluster)
        marker_cluster.add_to(map)
        feature_passlines.add_to(map)
        feature_skipshaler.add_to(map)
        oljetankskip.add_to(map)
        kjemikalie_produkttankskip.add_to(map)
        gasstankskip.add_to(map)
        bulkskip.add_to(map)
        stykkgods_roro_skip.add_to(map)
        konteinerskip.add_to(map)
        passasjerbat.add_to(map)
        ropax_skip.add_to(map)
        cruiseskip.add_to(map)
        offshore_supplyskip.add_to(map)
        andre_offshorefartoy.add_to(map)
        bronnbat.add_to(map)
        slepefartoy.add_to(map)
        andre_servicefartoy.add_to(map)
        fiskefartoy.add_to(map)
        annet.add_to(map)

        folium.LayerControl(collapsed=False).add_to(map)

        minimap = plugins.MiniMap()

        map.add_child(minimap)
        map.add_child(folium.LatLngPopup())

        map.save(filepath)
def add_minimap(map_name):
    # Plugin for mini map
    minimap = plugins.MiniMap(toggle_display = True)
Exemple #26
0
    def get_context_data(self, **kwargs):
        context = super(AgentsView, self).get_context_data(**kwargs)
        figure = folium.Figure()
        m = folium.Map(location=[48.383022, 31.1828699],
                       zoom_start=6,
                       tiles='OpenStreetMap',
                       control_scale=True)
        m.add_to(figure)

        # # add tiles to map, Create a tile layer to append on a Map
        # folium.raster_layers.TileLayer('Open Street Map').add_to(m)
        # folium.raster_layers.TileLayer('Stamen Terrain').add_to(m)
        # folium.raster_layers.TileLayer('Stamen Toner').add_to(m)
        # folium.raster_layers.TileLayer('Stamen Watercolor').add_to(m)
        # folium.raster_layers.TileLayer('CartoDB Positron').add_to(m)
        # folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(m)

        # # add layer control to show different maps
        # folium.LayerControl().add_to(m)

        # add minimap to map
        minimap = plugins.MiniMap(toggle_display=True)
        m.add_child(minimap)

        # add full screen button to map
        plugins.Fullscreen(position='topright').add_to(m)
        draw = plugins.Draw(export=True)

        # add draw tools to map
        draw.add_to(m)
        # display(m)
        for agent in self.get_queryset():
            if agent.vehicle.vehicle_code == '30':
                color = 'orange'
                icon = 'fa-truck'
            elif agent.vehicle.vehicle_code == '20':
                color = 'green'
                icon = 'fa-train'
            elif agent.vehicle.vehicle_code == '10':
                color = 'blue'
                icon = 'fa-anchor'
            elif agent.vehicle.vehicle_code == '40':
                color = 'purple'
                icon = 'fa-plane'
            elif agent.vehicle.vehicle_code == '70':
                color = 'gray'
                icon = 'fa-gus-pump'
            folium.Marker(location=[agent.latitude, agent.longitude],
                          tooltip='Натисніть щоб дізнатися більше',
                          popup=agent.name + ' ' + agent.notes,
                          icon=folium.Icon(color=color, icon=icon,
                                           prefix='fa')).add_to(m)

        m = m._repr_html_()
        figure.render()

        context['agents'] = Agent.objects.all()
        context['country_counts'] = Agent.objects.values('country').annotate(
            Count('country'))
        context['sea'] = Agent.objects.filter(vehicle__vehicle_code='10')
        context['air'] = Agent.objects.filter(vehicle__vehicle_code='40')
        context['map'] = m
        return context
Exemple #27
0
     - fill_color : 원의 안쪽 색깔 (색상코드표 사용 가능)
"""


# 4-3. folium plugin 활용하기
"""
    참조사이트(1) : https://dailyheumsi.tistory.com/85
    참조사이트(2) : https://dailyheumsi.tistory.com/92
"""

# 4-3-1. 마커 클러스터 만들기
data = data_pplace[["위도","경도"]].values  # 위도, 경도를 array로 만들기
plugins.MarkerCluster(data).ag dd_to(map_pplace)  # 마커 클러스터 삽입

# 4-3-2. 미니맵 만들기
minimap = plugins.MiniMap()
map_cctv.add_child(minimap)

# 4-3-4. 히트맵 만들기
from folium.plugins import HeatMap
HeatMap(data.tolist()).add_to(map_pplace)

# 4-3-5. 마우스 포지션(위도, 경도) 찾기 기능
from folium.plugins import MousePosition
MousePosition().add_to(map_pplace)

# 4-3-6. 측정도구 기능
from folium.plugins import MeasureControl
map_pplace.add_child(MeasureControl())

# 4-3-7. 그림 그리기 기능 (이거 되게 자주 쓰일듯!!!!!!)
Exemple #28
0
def test():
    start_coords = (16.79631, 96.16469)
    map_tem = folium.Map(location=start_coords, zoom_start=14, control_scale=True)
    #Search Control
    #fg = folium.FeatureGroup("Drawn Layer").add_to(map_tem) #comment this if written under Drawing Feature
    #plugins.Search(fg, search_label="shape_name", collapsed=True, placeholder='Search'+' '*10).add_to(map_tem)
    #sc = folium.MacroElement().add_to(map_tem)
    #sc._template = elements["search_control"] #not apper "Drawn Layer" on layer control
    #Full Screen
    plugins.Fullscreen().add_to(map_tem)
    #Locate Control
    plugins.LocateControl().add_to(map_tem)
    #Add the draw
    fg = folium.FeatureGroup("Drawn Layer").add_to(map_tem) #uncomment if Search Control is written under Drawing Feature
    plugins.Search(fg, search_label="shape_name", collapsed=True, placeholder='Search'+' '*10).add_to(map_tem)
    #plugins.Draw(export=True, filename='data.geojson', position='topleft', draw_options=None, edit_options=None).add_to(map_tem)
    dc = folium.MacroElement().add_to(map_tem)
    de = folium.MacroElement().add_to(map_tem)
    dc._template = elements["draw_control"]
    de._template = elements["drawn_element"]

    #fg = folium.FeatureGroup("Drawn Layer").add_to(map_tem) #comment this if written under Drawing Feature
    #plugins.Search(fg, search_label="shape_name", collapsed=True, placeholder='Search'+' '*10).add_to(map_tem)
    #sc = folium.MacroElement().add_to(map_tem)
    #sc._template = elements["search_control"] #not appear "Drawn Layer" on layer control
    #de = folium.MacroElement().add_to(map_tem)
    #de._template = elements["drawn_element"]

    #Mouse position
    fmtr = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};"
    plugins.MousePosition(position='topright', separator=' | ', prefix="Mouse:", \
                          lat_formatter=fmtr, lng_formatter=fmtr).add_to(map_tem)
    #Add measure tool
    plugins.MeasureControl(position='bottomleft', primary_length_unit='meters', secondary_length_unit='miles',\
                           primary_area_unit='sqmeters', secondary_area_unit='acres').add_to(map_tem)

    # Add custom basemaps
    for k in basemaps:
        basemaps[k].add_to(map_tem)

    #folium.raster_layers.TileLayer('Open Street Map').add_to(map_tem)
    #folium.TileLayer('Stamen Terrain', show=False).add_to(map_tem)
    #folium.TileLayer('Stamen Toner', overlay=True, show=False).add_to(map_tem)
    #folium.TileLayer('Stamen Watercolor', overlay=True, show=False).add_to(map_tem)
    #folium.TileLayer('CartoDB Positron', overlay=True, show=False).add_to(map_tem)
    #folium.TileLayer('CartoDB Dark_Matter', overlay=True, show=False).add_to(map_tem)

    # Add a layer control panel to the map
    map_tem.add_child(folium.LayerControl()) #this code must be here
    #folium.LayerControl().add_to(map_tem) #same with map_tem.add_child(folium.LayerControl())
    #Add minimap
    plugins.MiniMap(tile_layer=basemaps['Google Satellite'], toggle_display=True, width=300, height=300, \
                    zoom_level_offset= -5, minimized=True).add_to(map_tem)
    gc = folium.MacroElement().add_to(map_tem)
    gc._template = elements["geocoder_control"]
    esri = folium.MacroElement().add_to(map_tem)
    esri._template = elements["esri_control"]

    #Style Override and Call Last must be on Last Line before Return
    style_override = folium.MacroElement().add_to(map_tem)
    style_override._template = elements["style_override"]
    call_last = folium.MacroElement().add_to(map_tem)
    call_last._template = elements["call_last"]

    #Test with GeoJSON
    a = folium.GeoJson(
        {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"shape_name":"A","shape_desc":"This is AAA"},"geometry":{"type":"Polygon","coordinates":[[[96.152344,16.789258],[96.152344,16.802076],[96.177149,16.802076],[96.177149,16.789258],[96.152344,16.789258]]]}}]})
    b = folium.GeoJson(
        {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"shape_name":"B","shape_desc":"This is BBB"},"geometry":{"type":"Polygon","coordinates":[[[96.128998,16.821302],[96.128998,16.856463],[96.160583,16.856463],[96.160583,16.821302],[96.128998,16.821302]]]}}]})
    #folium.features.GeoJsonPopup(fields=['shape_name', 'shape_desc'], labels=False).add_to(a)
    fg.add_child(a)
    fg.add_child(b)

    map_tem.save(os.path.join(os.getcwd(), "app", "static", "map.html"))
    return render_template("test.html", bottom=1)
# FILTER2
uk_potvrdenih = df_potvrdeni.iloc[:, -1].values
uk_umrlih = df_umrli.iloc[:, -1].values
uk_oporavljenih = df_oporavljeni.iloc[:, -1].values

m = folium.Map(location=[52.954784, -1.158109], zoom_start=5)

#### TYPES OF MAPS
folium.raster_layers.TileLayer('Stamen Terrain').add_to(m)
folium.raster_layers.TileLayer('Stamen Toner').add_to(m)
folium.raster_layers.TileLayer('Stamen Watercolor').add_to(m)
folium.raster_layers.TileLayer('CartoDB Positron').add_to(m)
folium.raster_layers.TileLayer('CartoDB Dark_Matter').add_to(m)

#### MINI MAP, ZOOM TOOLS
minimap = plugins.MiniMap(toggle_display=True)
m.add_child(minimap)
plugins.ScrollZoomToggler().add_to(m)
plugins.Fullscreen(position='topright').add_to(m)

#### GET LAT AND LONG TOOLS
m.add_child(folium.LatLngPopup())

#### MEASURING TOOLS
measure_control = plugins.MeasureControl(position='topleft',
                                         active_color='red',
                                         completed_color='blue',
                                         primary_length_unit='metres')
m.add_child(measure_control)

#### DRAWING TOOLS
Exemple #30
0
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = HTMLmapDialog()
            if self.dlg.radioButton.isChecked():
                self.dlg.pushButton_1.clicked.connect(
                    self.atualizarCoordenadaPartidaOSM)
                self.dlg.pushButton_2.clicked.connect(
                    self.atualizarCoordenadaChegadaOSM)
            if self.dlg.radioButton_2.isChecked():
                self.dlg.pushButton_1.clicked.connect(
                    self.atualizarCoordenadaPartidaGoogle)
                self.dlg.pushButton_2.clicked.connect(
                    self.atualizarCoordenadaChegadaGoogle)
            self.dlg.horizontalSlider.setValue(16)

            with open(
                    r'C:\OSGeo4W64\apps\qgis\python\plugins\htmlmap\Base\fontawesone.txt',
                    "r") as f:
                f.readline()
                for x in f:
                    comboText = self.dlg.comboBox_4.addItem(x)
                    comboText = self.dlg.comboBox_7.addItem(x)
                    comboText = self.dlg.comboBox_10.addItem(x)
            icon_color = {
                'beige', 'black', 'blue', 'cadetblue', 'darkblue', 'darkgreen',
                'darkpurple', 'darkred', 'gray', 'green', 'lightblue',
                'lightgray', 'lightgreen', 'lightred', 'orange', 'pink',
                'purple', 'red', 'white'
            }
            add_icon_color = self.dlg.comboBox_3.addItems(icon_color)
            add_icon_color = self.dlg.comboBox_8.addItems(icon_color)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            latPartida = self.dlg.lineEdit_5.text()
            lat = float(latPartida)
            longPartida = self.dlg.lineEdit_6.text()
            long = float(longPartida)
            if self.dlg.mGroupBox_8.isChecked():
                latChegada = self.dlg.lineEdit_7.text()
                lat2 = float(latChegada)
                longChegada = self.dlg.lineEdit_8.text()
                long2 = float(longChegada)
                latcentral = (lat + lat2) / 2
                longcentral = (long + long2) / 2
                lat = latcentral
                long = longcentral

    #CRIAR O MAPA/TILE
            tiles = ('Open Street Map', 'Stamen Terrain', 'Stamen Toner',
                     'Stamen Watercolor', 'CartoDB Positron',
                     'CartoDB Dark_Matter')

            #IMAGEM DE SATÉLITE GOOGLE
            zoom = self.dlg.horizontalSlider.value()
            m = folium.Map(location=[lat, long],
                           zoom_start=zoom,
                           tiles=None,
                           prefer_canvas=True)
            if self.dlg.comboBox.currentText() == 'Google Maps':
                folium.raster_layers.TileLayer(
                    tiles='http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
                    attr='google',
                    name='Google Maps',
                    max_zoom=20,
                    subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
                    overlay=False,
                    control=True,
                ).add_to(m)
            if self.dlg.comboBox.currentText() == 'Google Earth':
                folium.raster_layers.TileLayer(
                    tiles='http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
                    attr='google',
                    name='Google Earth',
                    max_zoom=20,
                    subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
                    overlay=False,
                    control=True).add_to(m)
            if self.dlg.comboBox.currentText(
            ) == 'Open Street Map' or 'Stamen Terrain' or 'Stamen Toner' or 'Stamen Watercolor' or 'CartoDB Positron' or 'CartoDB Dark_Matter':
                folium.raster_layers.TileLayer(
                    tiles=self.dlg.comboBox.currentText(),
                    attr='google',
                    name=self.dlg.comboBox.currentText(),
                    max_zoom=20,
                    control_scale=True).add_to(m)

    #MINIMAP
            if self.dlg.checkBox.isChecked():
                minimap = plugins.MiniMap(position='bottomright',
                                          toggle_display=True,
                                          width=100,
                                          height=100,
                                          zoom_level_offset=-4,
                                          center_fixed=False,
                                          zoom_animation=True,
                                          minimized=False)
                m.add_child(minimap)

    #DESENHAR NA TELA
            if self.dlg.checkBox_2.isChecked():
                draw = plugins.Draw(position='bottomright', export=True)
                draw.add_to(m)

    #MEDIÇÃO EM TELA DE DISTANCIA E ÁREA
            if self.dlg.checkBox_3.isChecked():
                measure_control = plugins.MeasureControl(
                    position='topright',
                    active_color='red',
                    completed_color='red',
                    primary_lenght_unit='meters')
                m.add_child(measure_control)

    # ADICIONAR ALGUMA IMAGEM NA TELA
            if self.dlg.checkBox_4.isChecked():
                url = self.dlg.mQgsFileWidget_5.filePath()
                FloatImage(url, bottom=92, left=1).add_to(m)

    #TELA CHEIA
            if self.dlg.checkBox_5.isChecked():
                plugins.Fullscreen(position='topleft').add_to(m)

    #LOCALIZAÇÃO DA PESSOA
            if self.dlg.checkBox_6.isChecked():
                plugins.LocateControl(position='topleft').add_to(m)
            if self.dlg.checkBox_8.isChecked():
                #    If you want get the user device positon after load the map, set auto_start=True
                plugins.LocateControl(auto_start=True).add_to(m)

    #LATITUDE E LONGITUDE PARA CLIQUES NO MAPA
            if self.dlg.checkBox_7.isChecked():
                m.add_child(folium.LatLngPopup())

            subgrupos = folium.FeatureGroup(name='Estilos de Mapas',
                                            control=False,
                                            show=False)
            m.add_child(subgrupos)
            if self.dlg.mGroupBox.isChecked():
                opcao1 = plugins.FeatureGroupSubGroup(
                    subgrupos, self.dlg.lineEdit_11.text(), show=True)
                m.add_child(opcao1)
            if self.dlg.mGroupBox_2.isChecked():
                opcao2 = plugins.FeatureGroupSubGroup(
                    subgrupos, self.dlg.lineEdit_12.text(), show=True)
                m.add_child(opcao2)
            if self.dlg.mGroupBox_3.isChecked():
                opcao3 = plugins.FeatureGroupSubGroup(
                    subgrupos, self.dlg.lineEdit_10.text(), show=True)
                m.add_child(opcao3)
            if self.dlg.mGroupBox_8.isChecked():
                opcao4 = plugins.FeatureGroupSubGroup(subgrupos,
                                                      'Rota',
                                                      show=True)
                m.add_child(opcao4)
#PONTO
            if self.dlg.mGroupBox.isChecked():
                PontosEntrada = self.dlg.mQgsFileWidget.filePath()
                PontosJSON = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Pontos_json.geojson'
                gj = folium.GeoJson(PontosJSON)
                popupPontos = self.dlg.lineEdit.text()
                processing.run(
                    "native:reprojectlayer", {
                        'INPUT': PontosEntrada,
                        'TARGET_CRS':
                        QgsCoordinateReferenceSystem('EPSG:4326'),
                        'OPERATION':
                        '+proj=pipeline +step +inv +proj=utm +zone=22 +south +ellps=GRS80 +step +proj=unitconvert +xy_in=rad +xy_out=deg',
                        'OUTPUT': PontosJSON
                    })

                for feature in gj.data['features']:
                    if feature['geometry']['type'] == 'Point':
                        if self.dlg.comboBox_2.currentText() == 'Pin':
                            icon = self.dlg.comboBox_4.currentText()
                            color = self.dlg.mColorButton_11.color().name()
                            icon_color = self.dlg.mColorButton_5.color().name()
                            folium.Marker(location=list(
                                reversed(feature['geometry']['coordinates'])),
                                          popup=popupPontos,
                                          icon=folium.Icon(
                                              icon=icon,
                                              color=color,
                                              icon_color=icon_color,
                                              prefix='fa')).add_to(opcao1)

                        if self.dlg.comboBox_2.currentText(
                        ) == 'Beautify Icon':
                            icon = self.dlg.comboBox_4.currentText()
                            icon_color = self.dlg.mColorButton_5.color().name()
                            color = 'transparent'
                            tamanho = self.dlg.doubleSpinBox_4.value()
                            icon_size = (tamanho, tamanho)
                            icon_plane = plugins.BeautifyIcon(
                                icon=icon,
                                icon_size=icon_size,
                                border_color='transparent',
                                background_color=color,
                                innerIconStyle=
                                'font-size:20px;padding-top:1px;',
                                text_color=icon_color)
                            folium.Marker(location=list(
                                reversed(feature['geometry']['coordinates'])),
                                          popup=popupPontos,
                                          icon=icon_plane).add_to(opcao1)

#LINHA
            if self.dlg.mGroupBox_2.isChecked():
                LinhaEntrada = self.dlg.mQgsFileWidget_2.filePath()
                LinhaJSON = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Linha_json.geojson'
                espessura = self.dlg.doubleSpinBox_5.value()
                color = self.dlg.mColorButton.color().name()
                borda = self.dlg.mColorButton_13.color().name()
                popupLinhas = self.dlg.lineEdit_9.text()
                processing.run(
                    "native:reprojectlayer", {
                        'INPUT': LinhaEntrada,
                        'TARGET_CRS':
                        QgsCoordinateReferenceSystem('EPSG:4326'),
                        'OPERATION':
                        '+proj=pipeline +step +inv +proj=utm +zone=22 +south +ellps=GRS80 +step +proj=unitconvert +xy_in=rad +xy_out=deg',
                        'OUTPUT': LinhaJSON
                    })
                styleLinha = {
                    "fillOpacity": 1,
                    'fillColor': borda,
                    'color': color,
                    "weight": espessura,
                    "opacity": 1.0
                }
                folium.GeoJson(LinhaJSON,
                               style_function=lambda x: styleLinha,
                               popup=popupLinhas).add_to(opcao2)
#POLÍGONO
            if self.dlg.mGroupBox_3.isChecked():
                PoligonoEntrada = self.dlg.mQgsFileWidget_3.filePath()
                popupPoligono = self.dlg.lineEdit_2.text()
                color = self.dlg.mColorButton_3.color().name()
                borda = self.dlg.mColorButton_2.color().name()
                transparencia = self.dlg.doubleSpinBox.value()
                PoligonoJSON = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Poligono_json.geojson'
                processing.run(
                    "native:reprojectlayer", {
                        'INPUT': PoligonoEntrada,
                        'TARGET_CRS':
                        QgsCoordinateReferenceSystem('EPSG:4326'),
                        'OPERATION':
                        '+proj=pipeline +step +inv +proj=utm +zone=22 +south +ellps=GRS80 +step +proj=unitconvert +xy_in=rad +xy_out=deg',
                        'OUTPUT': PoligonoJSON
                    })
                stylePoligono = {
                    'fillColor': color,
                    "fillOpacity": transparencia,
                    'color': borda,
                    "weight": self.dlg.doubleSpinBox_2.value()
                }
                folium.GeoJson(
                    PoligonoJSON,
                    style_function=lambda x: stylePoligono).add_to(opcao3)

    #ADICIONAR IMAGEM - CERTO
    #        url = 'http://leafletjs.com/examples/custom-icons/{}'.format
    #        icon_image = url('leaf-red.png')
    #        icon3d = 'https://www.pngfind.com/pngs/m/218-2181815_download-setas-em-3d-png-images-background-setas.png'

    #        icon = CustomIcon(icon3d,icon_size=(19,47))
    #        marker = folium.Marker(location=[-25.4528, -49.2323],icon=icon,popup='Árvore')
    #        m.add_child(marker)

    #    icon_plane = plugins.BeautifyIcon(icon='tree', border_color='transparent', backgroundColor = 'transparent', iconSize= (22,22), border_width = 0.1, text_color='#83ca57',inner_icon_style='font-size:20px;padding-top:1px;')
    #    icon_number = plugins.BeautifyIcon(iconSize = (15, 15), border_width = 0, text_color='#000000', backgroundColor = 'transparent', number='A',inner_icon_style='font-size:15px')
    #    coord_arvores = [-25.4523, -49.2326]
    #    folium.Marker(location=coord_arvores,popup='Árvore', icon=icon_plane).add_to(m)
    #    folium.Marker(location=[-25.4527, -49.2331],popup='Bloco', icon=icon_number).add_to(m)
    #folium.LayerControl(collapsed=True).add_to(m)

    #icon3d = r'C:\Users\fabri\Desktop\Imagem1.svg'
    #icon = CustomIcon(icon3d,icon_size=(19,47))
    #marker = folium.Marker(location=[-25.4528, -49.2323],icon=icon,popup='Árvore')
    #m.add_child(marker)

#ORIGEM
            latPartida = self.dlg.lineEdit_5.text()
            latPartida = float(latPartida)
            longPartida = self.dlg.lineEdit_6.text()
            longPartida = float(longPartida)
            startPoint = '%s, %s [EPSG:4326]' % (
                longPartida, latPartida)  #'-46.505448,-18.578563 [EPSG:4326]'
            if self.dlg.comboBox_9.currentText() == 'Pin':
                icon = self.dlg.comboBox_7.currentText()
                color = self.dlg.comboBox_3.currentText()
                icon_color = self.dlg.mColorButton_7.color().name()
                folium.Marker(location=[latPartida, longPartida],
                              popup='Início',
                              icon=folium.Icon(icon=icon,
                                               color=color,
                                               icon_color=icon_color,
                                               prefix='fa')).add_to(m)

            if self.dlg.comboBox_9.currentText() == 'Beautify Icon':
                icon = self.dlg.comboBox_7.currentText()
                #color = self.dlg.comboBox_7.currentText()
                color = 'transparent'
                icon_color = self.dlg.mColorButton_7.color().name()
                icon_size = (10, 10)
                icon_plane = plugins.BeautifyIcon(
                    icon=icon,
                    prefix='fa',
                    icon_size=icon_size,
                    border_color='transparent',
                    background_color=color,
                    innerIconStyle='font-size:20px;padding-top:1px;',
                    text_color=icon_color)
                folium.Marker(location=[latPartida, longPartida],
                              popup='Início',
                              icon=icon_plane).add_to(m)
#ROTA
            if self.dlg.mGroupBox_8.isChecked():
                latPartida = self.dlg.lineEdit_5.text()
                latPartida = float(latPartida)
                longPartida = self.dlg.lineEdit_6.text()
                longPartida = float(longPartida)
                latChegada = self.dlg.lineEdit_7.text()
                latChegada = float(latChegada)
                longChegada = self.dlg.lineEdit_8.text()
                longChegada = float(longChegada)

                lat, long = [round(latPartida, 3),
                             round(latChegada, 3)
                             ], [round(longPartida, 3),
                                 round(longChegada, 3)]
                minlong, maxlong, minlat, maxlat = [
                    min(long) + 0.3,
                    max(long) - 0.3,
                    min(lat) + 0.3,
                    max(lat) - 0.3
                ]
                extensao = '%s, %s, %s, %s [EPSG:4326]' % (minlong, maxlong,
                                                           minlat, maxlat)
                redeOSM = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/Curitiba_vias01.shp'
                #malhaRota = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/cortado.gpkg'
                #processing.run("native:extractbyextent", {'INPUT':redeOSM,'EXTENT':extensao,'CLIP':False,'OUTPUT':malhaRota})

                startPoint = '%s, %s [EPSG:4326]' % (
                    longPartida, latPartida
                )  #'-46.505448,-18.578563 [EPSG:4326]'
                finalPoint = '%s, %s [EPSG:4326]' % (
                    longChegada, latChegada
                )  #'-46.507785,-18.577713 [EPSG:4326]'
                Ponto2 = '%s, %s' % (longChegada, latChegada)
                if self.dlg.comboBox_12.currentText() == 'Pin':
                    icon = self.dlg.comboBox_10.currentText()
                    color = self.dlg.comboBox_8.currentText()
                    icon_color = self.dlg.mColorButton_8.color().name()
                    folium.Marker(location=[latChegada, longChegada],
                                  popup='Chegada',
                                  icon=folium.Icon(icon=icon,
                                                   color=color,
                                                   icon_color=icon_color,
                                                   prefix='fa')).add_to(opcao4)

                if self.dlg.comboBox_12.currentText() == 'Beautify Icon':
                    icon = self.dlg.comboBox_10.currentText()
                    icon_color = self.dlg.mColorButton_8.color().name()
                    color = 'transparent'
                    icon_size = (10, 10)
                    icon_plane = plugins.BeautifyIcon(
                        icon=icon,
                        icon_size=icon_size,
                        border_color='transparent',
                        background_color=color,
                        innerIconStyle='font-size:20px;padding-top:1px;',
                        text_color=icon_color)
                    folium.Marker(location=[latChegada, longChegada],
                                  popup='Chegada',
                                  icon=icon_plane).add_to(opcao4)

                rota = 'C:/OSGeo4W64/apps/qgis/python/plugins/htmlmap/Base/rota.geojson'
                processing.run(
                    "native:shortestpathpointtopoint", {
                        'INPUT': redeOSM,
                        'STRATEGY': 0,
                        'DIRECTION_FIELD': None,
                        'VALUE_FORWARD': '',
                        'VALUE_BACKWARD': '',
                        'VALUE_BOTH': '',
                        'DEFAULT_DIRECTION': 2,
                        'SPEED_FIELD': None,
                        'DEFAULT_SPEED': 50,
                        'TOLERANCE': 0,
                        'START_POINT': startPoint,
                        'END_POINT': finalPoint,
                        'OUTPUT': rota
                    })

                with open(rota) as f:
                    data = json.load(f)
                for feature in data['features']:
                    coordenadasRota = (feature['geometry']['coordinates'])
                    coord_list = []
                for coord_pair in coordenadasRota:
                    json_coord_pair = {}
                    json_coord_pair = [(coord_pair[1]), (coord_pair[0])]
                    coord_list.append(json_coord_pair)

                    cor_rota = self.dlg.mColorButton_4.color().name()
                    cor_simbolo = self.dlg.mColorButton_6.color().name()

                    if self.dlg.mGroupBox_10.isChecked():
                        formato_simbolo = self.dlg.comboBox_5.currentText()
                        if self.dlg.comboBox_5.currentText() == 'Arredondado':
                            formato_simbolo = 'round'
                        if self.dlg.comboBox_5.currentText() == 'Quadrado':
                            formato_simbolo = 'butt'
                        if self.dlg.comboBox_5.currentText() == 'Retangular':
                            formato_simbolo = 'square'

                        juncao = self.dlg.comboBox_6.currentText()
                        if self.dlg.comboBox_6.currentText() == 'Arredondado':
                            juncao = 'round'
                        if self.dlg.comboBox_6.currentText() == 'Reto':
                            juncao = 'mitter'
                        if self.dlg.comboBox_6.currentText() == 'Cortado':
                            juncao = 'bevel'

                        plugins.AntPath(
                            [coord_list],
                            popup='Rota',
                            color=cor_rota,
                            weight=self.dlg.doubleSpinBox_8.value(),
                            opacity=1,
                            delay=self.dlg.spinBox_3.value(),
                            line_cap=formato_simbolo,
                            line_join=juncao,
                            dash_array=[10, 20],
                            pulse_color=cor_simbolo,
                            reverse=True,
                            hardwareAccelerated=True).add_to(opcao4)
                    else:
                        plugins.AntPath(
                            [coord_list],
                            popup='Rota',
                            color=cor_rota,
                            weight=self.dlg.doubleSpinBox_8.value(),
                            opacity=1,
                            pulse_color=cor_rota,
                            delay=0).add_to(opcao4)

    #SALVAR MAPA
            folium.LayerControl(collapsed=True).add_to(m)
            salvarHTML = self.dlg.mQgsFileWidget_4.filePath() + ".html"
            m_save = m.save(salvarHTML)
            message = ("Finalizado: O arquivo foi processado e salvo.")
            self.iface.messageBar().pushMessage(message, level=0, duration=10)