Example #1
0
def showEnumerateMarkers(fichier):
    df = pd.read_csv(fichier, encoding='utf-16',
                     sep='\t')  # Lecture du fichier d'adresses
    # Carte
    m = folium.Map(
        [43.9351691, 6.0679194],
        zoom_start=6)  # La localisation de départ pour cadrer les résultats
    m_Controle = plugins.MeasureControl(position='topleft',
                                        active_color='blue',
                                        completed_color='red',
                                        primary_length_unit='meters')
    m.add_child(m_Controle)
    # icons utilisant plugins.BeautifyIcon
    for (index, row) in df.iterrows():
        folium.Marker(location=[row['Latitudes'], row['Longitudes']],
                      popup=row['Zone DNS'],
                      tooltip=row['Adresses'],
                      icon=plugins.BeautifyIcon(
                          number=row['Occurrences'],
                          border_color='blue',
                          border_width=1,
                          text_color='red',
                          inner_icon_style='margin-top:0px;')).add_to(m)
    return m.save(outfile='outputs/EnumerateMarkersZoneDNS.html'
                  )  # Le fichier de sortie est une map au format "html"
def top_rated_by_country_map():
    url = 'data/custom.geo.json'
    world_geo = f'{url}'
    world_map = folium.Map(min_zoom=1,
                           max_zoom=6,
                           zoom_start=2,
                           location=(40, 15))

    conn = sqlite3.connect("data/movies.db")
    df = pd.read_sql_query(
        "Select *, Count(m.country) as count from Country c Join Location l on (c.country_id = l.id) Join Movies m on (c.country_id = m.country) where m.rank>=1 and m.rank<=250 group by m.country",
        conn)
    # df.dropna(axis='rows',inplace=True)
    df['e'] = df.iloc[:, 2:31].sum(axis=1)
    df = df[['country_name', 'iso_2', 'iso_3', 'long', 'lat', 'e', 'count']]
    # df.dropna(axis='columns',inplace=True)
    df = df[df['e'] != 0]
    conn.close()

    choropleth = folium.Choropleth(
        geo_data=world_geo,
        name='Number of Produced Movies',
        data=df,
        columns=['iso_3', 'e'],
        key_on='feature.properties.iso_a3',
        fill_color='YlGn',
        fill_opacity=0.7,
        line_opacity=0.2,
        bins=8,
        legend_name='Number of Produced Movies').add_to(world_map)

    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(fields=['sovereignt'], labels=False))

    incidents = plugins.MarkerCluster(
        name='Distribution of 250 Top Rated Movies').add_to(world_map)

    for lat, lng, label, in zip(df.lat, df.long, df['count']):
        for i in range(label):
            folium.Marker(
                location=[lat, lng],
                icon=plugins.BeautifyIcon(icon="leaf",
                                          iconSize=[36, 36],
                                          background_color="#87CEFA",
                                          border_color="#B0E0E6",
                                          borderWidth=5,
                                          inner_icon_style='size : 18px',
                                          number=label),
                popup=label,
            ).add_to(incidents)
        i += 1

    world_map.add_child(incidents)

    folium.LayerControl().add_to(world_map)

    return world_map
def test_beautify_icon():
    m = folium.Map([30., 0.], zoom_start=3)
    # BeautifyIcons
    ic1 = plugins.BeautifyIcon(
        icon='plane', border_color='#b3334f', text_color='#b3334f')
    ic2 = plugins.BeautifyIcon(border_color='#00ABDC',
                               text_color='#00ABDC',
                               number=10,
                               inner_icon_style='margin-top:0;')

    # Markers, add icons as keyword argument
    bm1 = folium.Marker(location=[46, -122],
                        popup='Portland, OR',
                        icon=ic1
                        ).add_to(m)

    bm2 = folium.Marker(
        location=[50, -121],
        icon=ic2
    ).add_to(m)

    m.add_child(bm1)
    m.add_child(bm2)
    m._repr_html_()

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

    # We verify that the script import is present.
    script = '<script src="https://rawcdn.githack.com/marslan390/BeautifyMarker/master/leaflet-beautify-marker-icon.js"></script>'  # noqa
    assert script in out

    # We verify that the css import is present.
    css = '<link rel="stylesheet" href="https://rawcdn.githack.com/marslan390/BeautifyMarker/master/leaflet-beautify-marker-icon.css"/>'  # noqa
    assert css in out

    # We verify that the Beautiful Icons are rendered correctly.
    tmpl = Template(u"""
                var {{this.get_name()}} = new L.BeautifyIcon.icon({{ this.options|tojson }})
                {{this._parent.get_name()}}.setIcon({{this.get_name()}});
            """)  # noqa

    assert normalize(tmpl.render(this=ic1)) in out
    assert normalize(tmpl.render(this=ic2)) in out
    def __visit_tree_and_add(self, terminal_parent, clade, fmap):
        if clade.name and clade.name in self.parsed_seqs:
            seq = self.parsed_seqs[clade.name]

            if "latitude" in seq and "longitude" in seq:
                self.__index += 1

                number = plugins.BeautifyIcon(border_color='#00ABDC',
                                              text_color='#00ABDC',
                                              number=self.__index,
                                              inner_icon_style='margin-top:0;')

                folium.Marker([seq["latitude"], seq["longitude"]],
                              popup=seq["description"],
                              tooltip=seq["genbank_accession"],
                              icon=number).add_to(fmap)
            else:
                self.__logger.log(
                    self.__module,
                    f'Coordinates missing for {seq["description"]}.')

        if clade.is_terminal():
            if terminal_parent in self.parsed_seqs and clade.name in self.parsed_seqs:
                start_seq = self.parsed_seqs[terminal_parent]
                end_seq = self.parsed_seqs[clade.name]

                valid_start = "latitude" in start_seq and "longitude" in start_seq
                valid_end = "latitude" in end_seq and "longitude" in end_seq

                if valid_start and valid_end:
                    self.__add_line(start_seq, end_seq, fmap)
        else:
            clade.ladderize()
            left_tree = clade.clades[0]
            right_tree = clade.clades[1]

            if left_tree.is_terminal() and right_tree.is_terminal():
                self.__visit_tree_and_add(terminal_parent, left_tree, fmap)
                self.__visit_tree_and_add(terminal_parent, right_tree, fmap)
            elif left_tree.is_terminal() and not right_tree.is_terminal():
                self.__visit_tree_and_add(terminal_parent, left_tree, fmap)
                self.__visit_tree_and_add(left_tree.name, right_tree, fmap)
            elif right_tree.is_terminal() and not left_tree.is_terminal():
                self.__visit_tree_and_add(terminal_parent, right_tree, fmap)
                self.__visit_tree_and_add(right_tree.name, left_tree, fmap)
            else:
                self.__visit_tree_and_add(terminal_parent, left_tree, fmap)
                self.__visit_tree_and_add(terminal_parent, right_tree, fmap)
Example #5
0
def get_hotel(mydict,city):
    loc2 = geocoder.osm(city)

    # map
    main_map = folium.Map(location=[loc2.lat, loc2.lng], zoom_start=13)
    folium.raster_layers.TileLayer('Open Street Map').add_to(main_map)

    # loop through dict
    for i in range (1,len(mydict)+1):
        folium.Marker(location=list(mydict[i].values())[i-1]
                      ,popup=list(mydict[i].keys())[i-1],tooltip=str(list(mydict[i].keys())[i-1]),
                     icon=plugins.BeautifyIcon(number=i,
                                               icon='bus',
                                            border_color='blue',
                                            border_width=0.5,
                                            text_color='red',
                                            inner_icon_style='margin-top:0px;')).add_to(main_map)
    main_map.save('templates/map.html')
    return render_template('index.html')
Example #6
0
def map_marker(final_course):
    map_line = []
    map_course = folium.Map(location=[37.545905, 127.016015], zoom_start=12)
    cnt = 1
    for i in final_course:
        print(i, course_default[i][0])
        map_line.append([course_default[i][1], course_default[i][2]])
        my_location = [course_default[i][1], course_default[i][2]]
        if course_default[i][0] == '현재위치': icon = 'user'
        elif course_default[i][0] == '마지막위치': icon = 'bed'
        else: icon = 'chevron-circle-down'

        folium.Marker(my_location, icon = plugins.BeautifyIcon(icon = icon, border_color='red', text_color='red'\
                      ,icon_shape = 'marker', border_width = 2),tooltip = str(cnt) + course_default[i][0]).add_to(map_course)
        cnt += 1

    folium.PolyLine(locations=map_line, color='red', weight=4,
                    line_opacity=1).add_to(map_course)
    htmlfilename = 'map_marker_test2.html'
    map_course.save(htmlfilename)
    htmltopng(htmlfilename)
for route in routes_array:
    marker_list = json.loads(base64.b64decode(route["RoutePointsBlob"]))
    marker_locations = []

    for marker in marker_list:
        route_points_count += 1

        marker_id = marker["Id"]
        marker_title = "Id:{}".format(marker_id)

        marker_lat = marker["Latitude"]
        marker_long = marker["Longitude"]
        marker_locations.append([marker_lat, marker_long])

        marker_icon = plugins.BeautifyIcon(icon='arrow-down',
                                           icon_shape='marker',
                                           background_color=route["Color"])
        marker_popup = "<b>Id: {}</b> <br/><br/> <b>Lat: {}</b> <br/><br/> <b>Long: {}</b>".format(
            marker_id, marker_lat, marker_long)
        folium.Marker([marker_lat, marker_long],
                      popup=marker_popup,
                      tooltip=marker_title,
                      icon=marker_icon).add_to(f_map)

    danger_line = folium.PolyLine(marker_locations,
                                  weight=10,
                                  color=route["Color"],
                                  opacity=0.8).add_to(f_map)

print("Total Markers: {}".format(route_points_count))
Example #8
0
def success():
    if request.method == 'POST':
        f = request.files['file']
        df_addresses = pd.read_csv(f)

        df_addresses.Zipcode = df_addresses.Zipcode.apply(str)
        df_addresses['full_address'] = df_addresses[
            'Address'] + ',' + df_addresses['City'] + ',' + df_addresses[
                'State'] + ',' + df_addresses['Zipcode'] + ',' + 'USA'
        df_addresses['sequence'] = df_addresses.groupby('Group').cumcount() + 1

        def set_value(row_number, assigned_value):
            return assigned_value[row_number]
# Create the dictionary

        event_dictionary = {
            'Anita Carson': 'pink',
            'Tim Edwards': 'yellow',
            'Johnathan Shaw': 'blue',
            'Josh Jennings': 'violet',
            'Andrew Burt': 'green',
            'Tony Bonetti': 'cadetblue'
        }

        df_addresses['Color'] = df_addresses['Group'].apply(
            set_value, args=(event_dictionary, ))
        key = '0ba6084e61384f88816ab2eaa53b1983'
        gmaps_key = OpenCageGeocode(key)
        df_addresses['Latitude'] = None
        df_addresses['Longitude'] = None
        list_lat = []  # create empty lists
        list_long = []
        for index, row in df_addresses.iterrows():
            geocode_result = gmaps_key.geocode(
                df_addresses['full_address'][index])
            lat = geocode_result[0]['geometry']['lat']
            long = geocode_result[0]['geometry']['lng']

            list_lat.append(lat)
            list_long.append(long)


# create new columns from lists

        df_addresses['Latitude'] = list_lat

        df_addresses['Longitude'] = list_long

        lat_mean = df_addresses['Latitude'].mean()
        long_mean = df_addresses['Longitude'].mean()

        df_group = df_addresses['Group'].unique()
        MEMP_COORDINATES = (lat_mean, long_mean)

        mapa = folium.Map(location=MEMP_COORDINATES, zoom_start=10)

        for grp_name, df_group in df_addresses.groupby('Group'):
            feature_group = folium.FeatureGroup(grp_name)
            for row in df_group.itertuples():
                folium.Marker(location=[row.Latitude, row.Longitude],
                              popup=('Address: ' + str(row.full_address) +
                                     '<br>'
                                     'Tech: ' + str(row.Group)),
                              icon=plugins.BeautifyIcon(
                                  number=str(row.sequence),
                                  border_width=2,
                                  iconShape='marker',
                                  inner_icon_style='margin-top:2px',
                                  background_color=row.Color,
                              )).add_to(feature_group)
            feature_group.add_to(mapa)

        folium.LayerControl().add_to(mapa)
        print(df_addresses)
        #f.save(f.filename)
        #return render_template("success.html", name = f.filename)
        return mapa._repr_html_()
                  color = 'black',
                  radius = i.area**(1.0/3.0),
                  fill = True, 
                  fill_color = 'gray').add_to(consultant_feature_group.add_to(base_map))


# In[ ]:


# icons using plugins.BeautifyIcon
for i in msa_metrics.head(30).itertuples():
    folium.Marker(location=[i.lat, i.lon],
                  popup=i.msa,
                  icon=plugins.BeautifyIcon(number=i.icon_num,
                                            border_color='blue',
                                            border_width=1,
                                            text_color='green',
                                            inner_icon_style='margin-top:0px;')).add_to(andrew_feature_group.add_to(base_map))


# In[ ]:


# icons using plugins.BeautifyIcon
# https://fontawesome.com/v4.7.0/icons/

dropyard_feature_group = folium.FeatureGroup(name = 'Werner Dropyards')
terminal_feature_group = folium.FeatureGroup(name = 'Werner Terminals')

for i in dropyards.itertuples():
    folium.Marker(location=[i.Latitude, i.Longitude],
Example #10
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)
Example #11
0
import pandas as pd
import matplotlib.pyplot as plt
import folium
import folium.plugins as plugins

m = folium.Map(location=[45.372, -121.6972],
               zoom_start=12,
               tiles='Stamen Terrain')

folium.Marker([45.372, -121.6972],
              icon=plugins.BeautifyIcon(icon='leaf', iconShape='marker'),
              draggable=True,
              popup='popup',
              tooltip='This is a beatifyMarker').add_to(m)
Example #12
0
    building_data = {"Latitude": [32.05], "Longitude": [8.58]}
    corp_data = pd.DataFrame(building_data, columns=["Latitude", "Longitude"])

    # Create Output csv files
    df.to_csv("coordinates.csv")
    broken_addresses.to_csv("broken_coordinates.csv")

    # Folium Groups
    customers = folium.FeatureGroup(name="Customers")
    ships = folium.FeatureGroup(name="Ships")
    headquarters = folium.FeatureGroup(name="Corporate Headquarters")
    heatmap = folium.FeatureGroup(name='Corona Virus Spread')

    # Icons of Every Group
    customers_icon = plugins.BeautifyIcon(icon='plane',
                                          border_color='#b3334f',
                                          text_color='#b3334f')

    # for row in df.full_address():
    labeled_popups = df["Address"].astype(str)

    # Create all Group's Icons from "https://fontawesome.com/v4.7.0/icons/"
    customers_icons = [
        folium.Icon(icon="user", prefix="fa", color='green')
        for _ in range(rows)
    ]
    ships_icons = [
        folium.Icon(icon="ship", prefix="fa", color='blue') for _ in range(1)
    ]
    headquarters_icons = [
        folium.Icon(icon="coffee", prefix="fa", color='orange')
covid = pd.read_csv('IDN-COVID19.csv')
covid.head()

maps1 = folium.Map(location=[3.100, 115.850], zoom_start=5)

confirmed = folium.FeatureGroup(name='Confirmed')
maps1.add_child(confirmed)

# icon
for i in covid.itertuples():
    confirmed.add_child(
        folium.Marker(location=[i.lat, i.long],
                      popup=i.Province_name,
                      icon=plugins.BeautifyIcon(
                          number=i.Confirmed_cases,
                          border_color='black',
                          border_width=2,
                          text_color='blue',
                          inner_icon_style='margin-top:0px;')))

recover = folium.FeatureGroup(name='Recovered')
maps1.add_child(recover)

# icon
for i in covid.itertuples():
    recover.add_child(
        folium.Marker(location=[i.lat, i.long],
                      popup=i.Province_name,
                      icon=plugins.BeautifyIcon(
                          number=i.Recovered_cases,
                          border_color='black',
                          border_width=2,
def create_map(cuisine, location, price):
    # create map with coordinates of location specified
    tm_map = folium.Map(location=COORDINATES.get(location), zoom_start=11)

    pos_df = pd.read_csv('data/datasets/topic_modelling/pos_bsns_' +
                         location.replace(" ", "").lower() + "_" +
                         cuisine.lower() + '.csv')
    neg_df = pd.read_csv('data/datasets/topic_modelling/neg_bsns_' +
                         location.replace(" ", "").lower() + "_" +
                         cuisine.lower() + '.csv')

    # get restaurants in specified price range only
    pos_df = pos_df[pos_df['RestaurantsPriceRange2'] == price]
    neg_df = neg_df[neg_df['RestaurantsPriceRange2'] == price]

    pos_topics = list(pos_df)[9:15]
    neg_topics = list(neg_df)[9:15]

    for i, row in enumerate(neg_df.itertuples(), 0):
        # negative topic probabilities
        neg_scores = neg_df.iloc[i, 9:15].tolist()

        # get star rating from positive topic data set
        positive = pos_df.loc[pos_df['business_id'] == row.business_id]
        pos_star = row.stars
        if not positive.empty:
            pos_star = positive['stars'].values[0]

        # get average star rating of negative and positive dataset
        avg_stars = (row.stars + pos_star) / 2

        # Create dynamically since some combinations have 5 topics instead of 6
        pos_html_topics = [''] * len(pos_topics)
        neg_html_topics = [''] * len(neg_topics)

        # get positive topics scores from positive topics dataset based on id from negative dataset
        positive = pos_df.loc[pos_df['business_id'] == row.business_id]
        pos_scores = [0] * len(pos_topics)
        if not positive.empty:
            pos_scores = positive.iloc[0, 9:15].tolist()

        # format html for popup
        for m in range(0, len(pos_topics)):
            pos_html_topics[m] = '{:18} {:.2f}%'.format(
                pos_topics[m].strip(), pos_scores[m] * 100)
        for n in range(0, len(neg_topics)):
            neg_html_topics[n] = '{:18} {:.2f}%'.format(
                neg_topics[n].strip(), neg_scores[n] * 100)

        pos_topics_text = 'Positive Topics<br>' + '<br>'.join(pos_html_topics)
        neg_topics_text = 'Negative Topics<br>' + '<br>'.join(neg_html_topics)
        stars_text = '<h3> Stars: ' + '{:.2f}'.format(avg_stars) + '</h3>'
        name_text = '<h3> Name: ' + row.name + '</h3>'
        popup_text = name_text + stars_text + '<p>' + pos_topics_text + '<br><br>' + neg_topics_text + '</p>'

        # set marker on map
        folium.Marker(location=[row.latitude, row.longitude],
                      popup=get_popup(popup_text),
                      icon=plugins.BeautifyIcon(
                          border_color='transparent',
                          background_color=star_color(avg_stars),
                          icon='circle',
                          icon_shape='marker',
                          text_color='#FFF')).add_to(tm_map)

        # only map 600 businesses to ensure faster rendering of map on dashboard
        if row.Index > 600:
            break

    # create color map, lower stars = red and higher stars = green
    colormap = cm.LinearColormap(['red', 'orange', 'yellow', 'green'],
                                 vmin=0,
                                 vmax=5)

    colormap.caption = 'Star Rating'
    tm_map.add_child(colormap)

    # save map as html
    file_name = location.replace(
        " ", "").lower() + "_" + cuisine.lower() + "_" + str(price) + ".html"
    tm_map.save('maps/' + file_name)