コード例 #1
0
def index():
    start_coords = (46.9540700, 142.7360300)
    folium_map = folium.Map(location=start_coords, zoom_start=14)
    # return folium_map._repr_html_()
    plugins.LocateControl(auto_start=True).add_to(folium_map)
    geojson = folium.GeoJson(states).add_to(folium_map)
    plugins.Search(geojson).add_to(folium_map)
    return render_template('foliumtest.html',
                           map=Markup(folium_map._repr_html_()))
コード例 #2
0
ファイル: generate_map.py プロジェクト: vandenbroucke/BRUBIKE
def GENERATE_MAP_MAIN_FUNCTION(path='./data/combined_data.tsv'):
	start=dt.now()
	bike_point_list=[]
	longitude_list=[]
	latitude_list=[]
	print('Generating map...')

	count=0
	with open(path) as tsvfile:
	  reader = csv.reader(tsvfile, delimiter='\t')
	  for row in reader:
	    if count !=0:
	      if not row[0] in bike_point_list:
	        bike_point_list.append(row[0])
	        longitude_list.append(float(row[1]))
	        latitude_list.append(float(row[2]))
	    count+=1
	        
	# Make a data frame with dots to show on the map
	data = pd.DataFrame({
	'lat':latitude_list,
	'lon':longitude_list,
	'name':bike_point_list
	})


	# Make an empty map
	m = folium.Map(location=[st.mean(longitude_list), st.mean(latitude_list)], tiles="OpenStreetMap", zoom_start=11.5,control_scale=True)
	plugins.Fullscreen(
    position='topright',
    title='Expand me',
    title_cancel='Exit me',
    force_separate_button=True
	).add_to(m)
	#Including some plugins to map
	#plugins.HeatMap(defining_heat_map_list()).add_to(m)
	plugins.LocateControl().add_to(m)

	# I can add marker one by one on the map
	for i in range(0,len(data)):
	    folium.Marker([data.iloc[i]['lon'], data.iloc[i]['lat']], popup=data.iloc[i]['name'],icon=folium.Icon(color='red', icon='info-sign')).add_to(m)
	 
	# Save it as html
	m.save('./map/bike_Brussels-points-map.html')

	print('The bike_Brussels-points-map.html file was already generated')
	print(dt.now()-start)
コード例 #3
0
def register_found():
    form = FoundForm()
    # TODO: 폼에서 발견 디비에 저장
    # TODO: Register Service 랑 연동
    start_coords = (37.49, 127.027)
    folium_map = folium.Map(
        location=start_coords,
        zoom_start=11,
    )
    plugins.LocateControl(auto_start=True).add_to(folium_map)  # 현재위치로 초기화
    folium_map.add_child(ClickForOneMarker(popup='습득위치'))
    if form.validate_on_submit():
        founditem = FoundedItem(current_user.id)
        collection = db.get_collection('founddata')
        collection.insert_one(founditem.to_dict())
        return redirect(url_for('lostfound.my_page'))
    return render_template('bootstrap/register.html', form=form, map=Markup(folium_map._repr_html_()))
コード例 #4
0
def index():
    start_coords = (37.49, 127.027)
    folium_map = folium.Map(
        # width='100%',
        # height='75%',
        min_zoom=7,
        location=start_coords,
        zoom_start=11,
        prefer_canvas=True,
    )
    skorea_provinces = folium.GeoJson(
        'user_folium/skorea-provinces-2018-geo.json',
        name='skorea-provinces',
        tooltip=folium.GeoJsonTooltip(
            fields=['name', 'base_year', 'name_eng', 'code'],
            aliases=['지역', '연도', '영문명', '지역코드'],
            localize=True
        )
    )
    plugins.LocateControl(auto_start=True).add_to(folium_map)  # 현재위치로 초기화

    skorea_municipalities = folium.GeoJson(
        'user_folium/skorea-municipalities-2018-geo.json',
        name='skorea-municipalities',
        tooltip=folium.GeoJsonTooltip(
            fields=['name', 'base_year', 'name_eng', 'code'],
            aliases=['지역', '연도', '영문명', '지역코드'],
            localize=True)
    )
    plugins.Search(
        layer=skorea_provinces,
        search_label='name',
        search_zoom=11,
        placeholder='province'
    ).add_to(folium_map)
    plugins.Search(
        layer=skorea_municipalities,
        search_label='name',
        search_zoom=11,
        placeholder='state'
    ).add_to(folium_map)

    # return render_template('v2temp/index.html', map=Markup(folium_map._repr_html_()))
    return render_template('bootstrap/folium_index.html', map=Markup(folium_map._repr_html_()))
コード例 #5
0
def register_lost():
    form = LostForm()
    # TODO: 폼데이터 분실 디비에 저장
    start_coords = (37.49, 127.027)
    folium_map = folium.Map(
        location=start_coords,
        zoom_start=11,
    )
    # geojson1 = folium.GeoJson(
    #     skorea_provinces_geo,
    #     name = 'skorea-provinces',
    # ).add_to(folium_map)
    plugins.LocateControl(auto_start=True).add_to(folium_map)  # 현재위치로 초기화
    folium_map.add_child(ClickForOneMarker(popup='분실위치'))
    if form.validate_on_submit():
        lostitem = LostedItem(form.itemname.data, form.category.data, form.place.data, form.latitude.data, form.longitude.data, form.lost_date.data, current_user.id, form.detail.data)
        collection = db.get_collection('lostdata')
        collection.insert_one(lostitem.to_dict())
        flash('등록되었습니다.')
        return redirect(url_for('lostfound.my_page'))
    return render_template('bootstrap/register.html', form=form, map=Markup(folium_map._repr_html_()))
コード例 #6
0
def index():
    form = TestForm()
    start_coords = (16.79631, 96.16469)
    map_tem = folium.Map(location=start_coords, zoom_start=14)
    if session.get("name") and session.get("latlng"):
        mark_place = list(map(float, session.get("latlng").split(",")))
        map_tem = folium.Map(location=mark_place, zoom_start=16)
        if session.get("locate"):
            cur_locate = list(map(float, session.get("locate").split(",")))
            mid_point = get_mid_point(cur_locate, mark_place)
            #To play zoom_start level here later
            map_tem = folium.Map(location=mid_point, zoom_start=12)
        msg_html = '''<b>Clicked Location</b>
                      <p>Latitude: {} <br/> Longitude: {}</p>
                   '''.format(*mark_place)
        message = folium.Html(msg_html, script=True)
        folium.Marker(
               mark_place,
               popup=folium.Popup(message, max_width=300, min_width=200),
               tooltip="Hello",
               icon=folium.Icon(color='red'),
               ).add_to(map_tem)
    #map_tem.add_child(folium.LatLngPopup())
    #map_tem.add_child(folium.ClickForMarker())
    map_tem.add_child(plugins.LocateControl())
    el = folium.MacroElement().add_to(map_tem)
    el._template = elements["set_latlng_locate"]
    map_tem.save(os.path.join(os.getcwd(), "app", "static", "map.html"))
    if form.validate_on_submit():
        session["name"] = form.name.data
        session["latlng"] = form.latlng.data
        session["locate"] = form.locate.data
        return redirect(url_for(".index"))
    return render_template('index.html', form=form,
                            name = session.get("name"),
                            latlng = session.get("latlng") )
コード例 #7
0
 def addLocateControl(self):
     plugins.LocateControl().add_to(self.my_map)
コード例 #8
0
            i = i + 1

        i = 0
        while i < len(data["match"]) - 1:
            points_a = [data["match"][i], data["match"][i + 1]]
            folium.PolyLine(
                points_a,
                color="blue",
                weight=2.5,
                opacity=1,
            ).add_to(match)
            i = i + 2

        folium.LayerControl(collapsed=False).add_to(m)  #rajout des boutons

        plugins.LocateControl().add_to(
            m)  #facultative juste pour connaitre sa position.

        #points_a = [[48.848067, 2.301280], [48.877505, 2.343289]]
        #folium.PolyLine(points_a, color="blue", weight=2.5, opacity=1).add_to(m)
        """features = [ #pour l'animation
        {
        'type': 'Feature',
        'geometry': {
            'type': 'LineString',
            'coordinates': line['coordonnee'],
        },
        'properties': {
            'times': line['date'],
            'style': {
                'color': line['color'] if 'color' in line else 'red',
                'weight': line['weight'] if 'weight' in line else 5
コード例 #9
0
def job_function():
    names = []
    addrs = []
    lats = []
    lngs = []
    stock_ats = []
    remain_stats = []
    created_ats = []

    for idx in range(len(input_addr)):
        url = storeAddrUrl + "?address=" + seoul + input_addr[idx]
        req = requests.get(url)
        json_data = req.json()
        store_list = json_data["stores"]

        for i in range(len(store_list)):
            if len(store_list[i]) != 9:
                continue

            if store_list[i]["name"] is None:
                names.append("name error")
            else:
                names.append(store_list[i]["name"])

            if store_list[i]["addr"] is None:
                addrs.append("addr error")
            else:
                addrs.append(store_list[i]["addr"])

            if store_list[i]["lat"] is None:
                lats.append(0)
            else:
                lats.append(store_list[i]["lat"])

            if store_list[i]["lng"] is None:
                lngs.append(0)
            else:
                lngs.append(store_list[i]["lng"])

            if store_list[i]["stock_at"] is None:
                stock_ats.append("NULL")
            else:
                stock_ats.append(store_list[i]["stock_at"][5:16])

            if store_list[i]["remain_stat"] is None:
                remain_stats.append("error")
            else:
                remain_stats.append(store_list[i]["remain_stat"])

            if store_list[i]["created_at"] is None:
                created_ats.append("NULL")
            else:
                created_ats.append(store_list[i]["created_at"][5:16])

        mp = folium.Map((37.566655, 126.978454), zoom_start=13)

        plugins.LocateControl(drawCircle=False, strings={
            "title": "현재위치"
        }).add_to(mp)

        for i in range(len(lats)):
            if remain_stats[i] == 'error' or remain_stats[i] == 'break':
                continue
            folium.Circle(
                location=[lats[i], lngs[i]],
                popup=folium.Popup('<strong>' + names[i] + '</strong><br>' +
                                   '마스크 수량: ' + amount[remain_stats[i]] +
                                   '<br>' + '입고 시간: ' + stock_ats[i] + '<br>' +
                                   '업데이트 시간: ' + created_ats[i],
                                   max_width=300),
                radius=20,
                color=col[remain_stats[i]],
                fill_color=col[remain_stats[i]]).add_to(mp)

        mp.save("./near_mask_by_addr.html")
コード例 #10
0
month2 = int(form.getvalue("l"))
year = int(form.getvalue("h"))
year2 = int(form.getvalue("m"))
time1 = (str(year) + '-' + str(month).zfill(2) + '-' + str(day1).zfill(2) +
         'T' + str(starthour).zfill(2) + ':' + str(startminute).zfill(2))
time2 = (str(year2) + '-' + str(month2).zfill(2) + '-' + str(day2).zfill(2) +
         'T' + str(finishhour).zfill(2) + ':' + str(finishminute).zfill(2))
d = int(zoom) * .001365

tend = time.strftime('%Y' + '-' + '%m' + '-' + '%d' + 'T' + '%H' + ':' + '%M' +
                     ':' + '%S')

m = folium.Map(location=[lat, lng], zoom_start=zoom, tiles=None, height=1000)
minimap = plugins.MiniMap()
m.add_child(minimap)
plugins.LocateControl(auto_start=True).add_to(m)
m.add_child(folium.LatLngPopup())

folium.raster_layers.TileLayer(
    tiles='http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
    attr='google',
    name='google street view',
    max_zoom=20,
    subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
    overlay=True,
    opacity=.66,
    transparent=True,
    control=True,
).add_to(m)

#########
コード例 #11
0
def folium_view(request, *args, **kwargs):

    #================================================== Model data================================================
    data = Webmap.object.all()[:50]
    m = folium.Map([29, -8.86], tiles='OpenStreetMap', zoom_start=5)
    html_string = m.get_root().render()
    test = folium.Html('<b>Hello world</b>', script=True)
    media_url = settings.MEDIA_ROOT
    #================================================External data json,gejson ...=======================================
    #jsondata= './webmap/static/communes.geojson'
    #commun=geopandas.read_file(jsondata)

    # ====================================================================Plugins===============================================
    #More Tiles
    folium.TileLayer('Stamen Watercolor').add_to(m)
    plugins.Fullscreen(position='bottomright',
                       title='Expand me',
                       title_cancel='Exit me',
                       force_separate_button=True).add_to(m)
    #plugins.Geocoder().add_to(m)
    plugins.LocateControl(auto_start=False, initial_zoom_level=10).add_to(m)

    #Measure control
    m.add_child(MeasureControl(position='topleft'))
    # Showing coordinates
    formatter = "function(num) {return L.Util.formatNum(num, 3) + ' º ';};"
    MousePosition(
        position='topright',
        separator=' | ',
        empty_string='NaN',
        lng_first=True,
        num_digits=20,
        prefix='Coordinates:',
        lat_formatter=formatter,
        lng_formatter=formatter,
    ).add_to(m)
    ###################################################################################################################################################################################################

    #############################################################################################################################################################################################
    #============================================================LayerGroups names
    fg = folium.FeatureGroup(name='All groups')
    m.add_child(fg)
    g1 = plugins.FeatureGroupSubGroup(fg, 'Group1')
    m.add_child(g1)
    g2 = plugins.FeatureGroupSubGroup(fg, 'Group2')
    m.add_child(g2)
    #------------ external data group json, geojson ...
    #extdata = plugins.FeatureGroupSubGroup(fg, 'communes',show=False)
    #m.add_child(extdata)

    # ===========================================================filtering using data ===========================================================================================================
    for y in data:
        grpopup = "<div class = popupdiv><img class='popupimg' src =" + y.link + '>' + "<br><p class='strong'>" + y.Nom + "</p>" + "<p class='desc'>" + y.Services + "</p></div>" + "<div class= ''>" + y.Description_si_disop + '</div> <br>' + "<span class='fas fa-map-pin'></span> " + y.Adress + '<br>' + "<div class= 'telpop'>" + y.Tel + '</div><br>'
        grimgurl = media_url + '/' + y.img.name
        grcustomIcon = folium.features.CustomIcon(grimgurl, icon_size=(30, 30))
        #-----------------------------------------Criterea 1 ---------------------------------------------------------
        if y.Nom == 'jarouub':
            folium.Marker(location=[y.geom.y, y.geom.x],
                          popup=grpopup,
                          radius=40,
                          icon=grcustomIcon).add_to(g1)

        #-----------------------------------------Criterea 2 -------------------------------------------------------------
        elif y.Nom == 'lol':
            folium.Marker(location=[y.geom.y, y.geom.x],
                          popup=grpopup,
                          radius=40,
                          icon=grcustomIcon).add_to(g2)

        #-------------------------For object that meet none of the Criterea ----------------------------------------------
        else:
            folium.Marker(location=[y.geom.y, y.geom.x],
                          popup=grpopup,
                          radius=40,
                          icon=grcustomIcon).add_to(fg)

        #--------------------------External data group -----------------------------------------------------------------

        #folium.GeoJson(commun,name='communes',overlay=False).add_to(extdata)

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

    #==============================================================This to add element inside the template generated by Folium ====================================================================

    style_statement = '''<style>    .leaflet-control{color:#f9f9f9; background-color:#000c } .leaflet-popup-content {margin: auto auto 10% auto;line-height: 1.4;text-align: center;} .popupimg{width:100%;margin-left:0px} .leaflet-popup-content-wrapper {width: 200px;text-align: center;}.leaflet-container {  /* all maps */height: 600px;width: 90%;margin: auto;z-index: 0;}@media(max-width:750px){.leaflet-container{height:500px;width:94%;}}#specialbigmap{height:800px;}/*Resizethe'display_raw'textbox*/.django-leaflet-raw-textarea{width:100%;}.bd-placeholder-img{font-size:1.125rem;text-anchor:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}@media(min-width:768px){.bd-placeholder-img-lg{font-size:3.5rem;}}.leaflet-container .leaflet-marker-pane img{max-width:none!important;max-height:none!important;border-radius:100%;border-style:double;border-width:0.4rem; border-color:#000}.leaflet-touch .leaflet-control-layers, .leaflet-touch .leaflet-bar{border:1pxsolidrgb(128,128,128);background-clip:padding-box;}.leaflet-popup-content-wrapper, .leaflet-popup-tip{background:#000000e8;color:#9aa3a6;box-shadow:03px14pxrgba(0,0,0,0.9);border-radius:1%;}.leaflet-popup-content{margin:5px19px1px19px;line-height:1.2;} .telpop{font-weight:bold}.servicespop{font-size:1.15rem;font-weight:bold;}.fas{margin-right:3%;color:#096cb1;font-size:medium;}.nompop{font-size:18px;position:relative;}.description{text-align:center;position:static;text-transform:uppercase;}.label{color:#096cb1;font-size:14px;font-family:'Roboto';}.leaflet-container{/*allmaps*/height:600px;width:90%;margin:auto;z-index:0;}@media(max-width:750px){.leaflet-container{height:500px;width:94%;}}#specialbigmap{height:800px;}/*Resizethe'display_raw'textbox*/.django-leaflet-raw-textarea{width:100%;}.bd-placeholder-img{font-size:1.125rem;text-anchor:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;} .leaflet-control-layers-toggle {background-image: url("/static/app/img/layers.png"); background-size: 60%;} .leaflet-touch .leaflet-bar {border: 1px solid rgba(0,0,0,0.1);background-color: #000000b8;} .strong {font-weight: 700;line-height: 1.6;font-size: 1.4rem;text-transform: uppercase;}  .leaflet-touch .leaflet-control-layers-toggle {width: 44px;height: 44px;background-color: #000000b8;}  .leaflet-touch .leaflet-bar a {border-bottom-left-radius: 2px;border-bottom-right-radius: 2px;border: 1px solid #000;} .strong{} .leaflet-popup-content-wrapper {width: 180px;text-align: center;height: auto;} .desc{}  .leaflet-popup-content p {margin: 10px 0;} .popupdiv{}
    .js-measuringprompt{color: #000 } .leaflet-touch .leaflet-control-measure .leaflet-control-measure-toggle{width: 30px;height: 30px;border-radius: 1px;border: solid 1px #000;}  </style>'''
    #Adding the elements t
    m.get_root().header.add_child(folium.Element(style_statement))
    m

    m.save('Map/templates/Folium.html')
    context = {'my_map': m}

    #=========================================================== Adding Django template tag in the beginning of Webmap template========================================================================
    filename = 'Map/templates/webmap.html'
    line = "{% load staticfiles %} {%load leaflet_tags%} {% leaflet_js%}{% leaflet_css%} <script src='{% static 'leaflet/leaflet/leaflet.js' %}'></script> <link rel='stylesheet' href='{% static 'leaflet/leaflet/leaflet.css' %}'>"
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

    return render(request, 'Folium.html', context)
コード例 #12
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)
コード例 #13
0
    addresses = pd.DataFrame(results)
    addresses.to_csv("addresses_results.csv")
    
    # Pass Data to Folium Map
    plugins.FastMarkerCluster(data=list(zip(correct_database['Latitude'].values, correct_database['Longitude'].values))).add_to(folium_map)
    
    # Create Fullscreen Button
    plugins.Fullscreen(
    position="topright",
    title="Expand me",
    title_cancel="Exit me",
    force_separate_button=True
    ).add_to(folium_map)

    # Create Minimap
    minimap = plugins.MiniMap(toggle_display=toggle_minimap_display)
    folium_map.add_child(minimap)

    # Locate Control
    folium.LayerControl().add_to(folium_map)
    plugins.LocateControl(auto_start=False).add_to(folium_map)

    # Create Draw Toolkit
    draw = plugins.Draw(export=toggle_draw_toolkit)
    draw.add_to(folium_map)
    folium_map.save("map.html")

else:
    print("Please insert a valid 'Number_of_Addresses' input, either 'One' or 'Many'.")

print("Process finished --- %s seconds ---" % (time.time() - start_time))
コード例 #14
0
def foliumMap():
    """ Function to render the map with the query chosen """

    map1 = folium.Map(location=edinburgh_coords,
                      tiles='openstreetmap',
                      zoom_control=False,
                      zoom_start=14)

    folium.TileLayer('cartodbpositron',
                     name="CartoDB Positron",
                     attr='Carto DB').add_to(map1)
    folium.TileLayer('cartodbdark_matter',
                     name="CartoDB DarkMatter",
                     attr='Carto DB').add_to(map1)
    folium.TileLayer('stamentoner', name="Stamen Toner",
                     attr='Stamen Toner').add_to(map1)

    plugins.LocateControl(auto_start=True,
                          flyTo=False,
                          returnToPrevBounds=True,
                          enableHighAccuracy=False,
                          position='topright').add_to(map1)
    plugins.Fullscreen(position='topright',
                       title='Foolish screen',
                       title_cancel='Return to normality',
                       force_separate_button=True).add_to(map1)

    #minimap_layer = folium.FeatureGroup(name="Minimap")
    user_results_layer = folium.FeatureGroup(name="User Location Results",
                                             show=user_results_show)
    results_layer = folium.FeatureGroup(name="Results", show=results_show)
    area_layer = folium.FeatureGroup(name='Areas of Edinburgh', show=False)
    bus_layer = folium.FeatureGroup(name='Bus Routes', show=False)
    bus_stop_layer = folium.FeatureGroup(name='Bus Stops', show=False)
    cinema_layer = folium.FeatureGroup(name='Cinemas')
    shop_layer = folium.FeatureGroup(name='Shops', show=False)
    restaurant_layer = folium.FeatureGroup(name='Restaurants', show=False)
    parking_layer = folium.FeatureGroup(name='Parking Zones', show=False)

    #plugins.MiniMap().add_to(minimap_layer)

    with open('../../../details.txt', 'r') as f:
        pwd = f.readline().strip()
    conn = cx_Oracle.connect(f"s0092179/{pwd}@geoslearn")
    c = conn.cursor()

    query, results_layer, ch1, ch2, ch3, ch4, ch5, ch6, ch7 = QueryBuilder(
        results_layer)

    c.execute(
        "SELECT a.ogr_fid, a.\"Type\", a.\"Zone_No\", sdo_util.to_geojson(a.ora_geometry) FROM parking_8307 a"
    )
    for row in c:
        id = int(row[0])
        colour = 'yellow'
        zone_no = row[2]
        park_type = row[1]
        if park_type == "Free":
            colour = 'green'
        elif park_type == "Controlled parking zone":
            colour = 'red'
        else:
            colour = 'orange'
        item = json.load(row[3])
        zone = folium.Choropleth(geo_data=item,
                                 line_color='orange',
                                 line_opacity=1,
                                 legend_name='Parking Areas',
                                 fill_opacity=0.3,
                                 fill_color=colour).add_to(parking_layer)
        folium.Tooltip(text=f"Zone {zone_no} is : {park_type}",
                       style=f"color:{colour}; font-weight:bold;",
                       sticky=False).add_to(zone)

    c.execute(
        "SELECT ogr_fid as id, naturalcom as name, sdo_util.to_geojson(ora_geometry) as jsongeometry FROM hoods_8307"
    )
    jsons_4326 = []
    for row in c:
        id = int(row[0])
        colour = colours[(id % 6)]
        style2 = {'fillColor': '#fc7303', 'color': colour, 'weight': 3}
        name = row[1]
        item = json.load(row[2])
        jsons_4326.append(item)
        area_id = f"area{row[0]}"
        area_name = row[1]
        name = folium.Choropleth(geo_data=item,
                                 tooltip=area_name,
                                 line_color='orange',
                                 line_opacity=1,
                                 legend_name='Edinburgh District',
                                 fill_opacity=0.6,
                                 fill_color=polycolours(id)).add_to(area_layer)
        folium.Tooltip(text=area_name, style="color:red;",
                       sticky=False).add_to(name)

    c.execute(
        "SELECT OGR_FID, sdo_util.to_geojson(ora_geometry) as jsongeometry from busroutes_8307"
    )
    for row in c:
        name = row[0]
        data = json.load(row[1])
        if name == 1:
            one = folium.GeoJson(
                data, name=name,
                style_function=lambda x: style1).add_to(bus_layer)
            folium.Popup(
                html=
                "<h3 style=\"min-width: 180px; color:red;\">Bus Route 1</h3><h4 style=\"color:red;\">Leith to Comiston</h4>"
            ).add_to(one)
        if name == 2:
            two = folium.GeoJson(
                data, name=name,
                style_function=lambda x: style3).add_to(bus_layer)
            folium.Popup(
                html=
                "<h3 style=\"min-width: 180px; color:blue;\">Bus Route 2</h3><h4 style=\"color:blue;\">Stockbridge to Newington</h4>"
            ).add_to(two)

    c.execute(
        "SELECT UNIQUE a.CINEMA_ID, a.NAME, b.title, c.time1, c.time2, c.time3, a.GEOM.sdo_point.x as lon, a.GEOM.sdo_point.y as lat from s1434165.cinemas a, s1434165.films b, s1434165.cinefilmrelation c where c.film_id = b.film_id and c.cinema_id = a.cinema_id"
    )

    cinemas_list = []

    cinema1 = None
    cinema2 = None
    cinema3 = None
    cinema4 = None
    cinema5 = None
    cinema6 = None
    cinema7 = None

    for row in c:
        (a, b, c2, d, e, f, g, h) = row
        cine = "cinema" + str(a)
        this_film = [f"{c2} : {d}, {e}, {f}"]
        if cine == 'cinema1':
            if cinema1 is None:
                cinema1 = Cinema(a, b, g, h)
                cinema1.films.append(this_film)
                cinemas_list.append(cinema1)
            else:
                cinema1.films.append(this_film)
        if cine == 'cinema2':
            if cinema2 is None:
                cinema2 = Cinema(a, b, g, h)
                cinema2.films.append(this_film)
                cinemas_list.append(cinema2)
            else:
                cinema2.films.append(this_film)
        if cine == 'cinema3':
            if cinema3 is None:
                cinema3 = Cinema(a, b, g, h)
                cinema3.films.append(this_film)
                cinemas_list.append(cinema3)
            else:
                cinema3.films.append(this_film)
        if cine == 'cinema4':
            if cinema4 is None:
                cinema4 = Cinema(a, b, g, h)
                cinema4.films.append(this_film)
                cinemas_list.append(cinema4)
            else:
                cinema4.films.append(this_film)
        if cine == 'cinema5':
            if cinema5 is None:
                cinema5 = Cinema(a, b, g, h)
                cinema5.films.append(this_film)
                cinemas_list.append(cinema5)
            else:
                cinema5.films.append(this_film)
        if cine == 'cinema6':
            if cinema6 is None:
                cinema6 = Cinema(a, b, g, h)
                cinema6.films.append(this_film)
                cinemas_list.append(cinema6)
            else:
                cinema6.films.append(this_film)
        if cine == 'cinema7':
            if cinema7 is None:
                cinema7 = Cinema(a, b, g, h)
                cinema7.films.append(this_film)
                cinemas_list.append(cinema7)
            else:
                cinema7.films.append(this_film)

    for cin in cinemas_list:
        popup_text = f"<h3 style=\"color:#f71e5b;\">{cin.name}</h3><h5>Showing Times</h5>"
        for film in cin.films:
            popup_text += f"<tr>{film[0]}</tr><br>"
        cin.popup_text = popup_text
        html = folium.Html(cin.popup_text, script=True)
        cin.popup_html = folium.Popup(html, max_width=2650)
        cin.marker = folium.Marker(
            [cin.lat, cin.lon],
            popup=cin.popup_html,
            icon=folium.Icon(
                color='#f71e5b',
                icon='glyphicon-facetime-video')).add_to(cinema_layer)

    # set defaults in case of errors
    longitude = -3.183051
    latitude = 55.948506
    distance = 0

    if "user-dist" in form:
        distance = form.getvalue("user-dist")
    #print(f"Name: {distance}")
    #print(f"Lat: {latitude}")
    #print(f"Lon: {longitude}")
    if int(distance) > 0:
        if "lat" in form:
            latitude = form.getvalue("lat")
        if "lon" in form:
            longitude = form.getvalue("lon")

        c, user_results_layer = user_location(c, latitude, longitude, distance,
                                              user_results_layer, cinemas_list)

    c.execute(
        "SELECT p.ROUTE, p.STOP_ID, p.STOP, p.GEOM.sdo_point.x as lon, p.GEOM.sdo_point.y as lat from s1983906.bus_stops p"
    )
    for row in c:
        route = row[0]
        stop_id = row[1]
        stop_name = row[2]
        lon = row[3]
        lat = row[4]
        if route == 1:
            popup_text = f"<h5 style=\"color:red;\">{stop_name}</h5>"
        if route == 2:
            popup_text = f"<h5 style=\"color:blue;\">{stop_name}</h5>"
        html = folium.Html(popup_text, script=True)
        popup = folium.Popup(html, max_width=2650)
        if route == 1:
            folium.Circle(location=[lat, lon],
                          radius=10,
                          tooltip=f"<h5 style=\"color:red;\">{stop_name}</h5>",
                          color='red',
                          weight=5,
                          fill=True).add_to(bus_stop_layer)
            #folium.Marker([lat, lon], popup=popup, icon=folium.Icon(color='red', icon='glyphicon-record')).add_to(bus_stop_layer)
        if route == 2:
            folium.Circle(
                location=[lat, lon],
                radius=10,
                tooltip=f"<h5 style=\"color:blue;\">{stop_name}</h5>",
                color='blue',
                weight=5,
                fill=True).add_to(bus_stop_layer)
            #folium.Marker([lat, lon], popup=popup, icon=folium.Icon(color='blue', icon='glyphicon-record')).add_to(bus_stop_layer)

    c.execute(
        "SELECT a.SHOP_ID, a.NAME, a.CATEGORY, a.OPEN, a.CLOSE, a.GEOM.sdo_point.x as lon, a.GEOM.sdo_point.y as lat from s1987402.shops a"
    )
    for row in c:
        id = row[0]
        name = row[1]
        category = row[2]
        opentime = time(int(row[3]), 0)
        formatted_open_time = opentime.strftime("%H:%M")
        closetime = time(int(row[4]), 0).strftime("%H:%M")
        formatted_close_time = closetime
        lon = row[5]
        lat = row[6]
        popup_text = f"<h3 style=\"color:#08a332;\">{name}</h3><tr><td><h5>Opening Times</h5>{formatted_open_time} to {formatted_close_time}</td></tr>"
        html = folium.Html(popup_text, script=True)
        popup = folium.Popup(html, max_width=2650)
        folium.Marker(
            [lat, lon],
            popup=popup,
            icon=folium.Icon(color='green',
                             icon='glyphicon-tag')).add_to(shop_layer)

    c.execute(
        "SELECT a.REST_ID, a.NAME, a.TYPE, a.OPEN, a.CLOSE, a.RATING, a.GEOM.sdo_point.x as lon, a.GEOM.sdo_point.y as lat from s1987402.restaurants a"
    )
    for row in c:
        id = row[0]
        name = row[1]
        type = row[2]
        opentime = time(int(row[3]), 0)
        formatted_open_time = opentime.strftime("%H:%M")
        closetime = time(int(row[4]), 0).strftime("%H:%M")
        formatted_close_time = closetime
        rating = row[5]
        lon = row[6]
        lat = row[7]
        popup_text = f"<h3 style=\"color:#14a0e0;\">{name}</h3><tr><td><h5>Opening Times</h5>{formatted_open_time} to {formatted_close_time}</td></tr>"
        html = folium.Html(popup_text, script=True)
        popup = folium.Popup(html, max_width=2650)
        folium.Marker([lat, lon],
                      popup=popup,
                      icon=folium.Icon(
                          color='blue',
                          icon='glyphicon-cutlery')).add_to(restaurant_layer)

    c.execute(query)
    for row in c:
        display = None
        name = row[0]
        try:
            if name == "Omni Centre":
                display = cinema1
            elif name == "Dominion":
                display = cinema2
            elif name == "Cameo":
                display = cinema3
            elif name == "Filmhouse":
                display = cinema4
            elif name == "Odeon Lothian":
                display = cinema5
            elif name == "Cineworld":
                display = cinema6
            elif name == "Scotsman Filmhouse":
                display = cinema7
            else:
                continue
        except ValueError:
            print("No matching cinema...")

        html = folium.Html(display.popup_text, script=True)
        display.popup_html = folium.Popup(html, max_width=2650)
        folium.Marker(
            row[1:],
            popup=display.popup_html,
            icon=folium.Icon(color='purple',
                             icon='glyphicon-ok')).add_to(results_layer)
    #    if display.geoclose == True:


#            folium.Tooltip(text==f"<h5>The {display.name} cinema is less<br> than <emp>{int(int(distance)/70)}</emp> minutes walk away</h5>",icon=folium.Icon(color='orange', icon='glyphicon-screenshot')).add_to(results)

    conn.close()

    if ch3 == 1:
        restaurant_layer.show = True
    if ch4 == 1:
        bus_layer.show = True
        bus_stop_layer.show = True
    if ch5 == 1:
        shop_layer.show = True
    if ch6 == 1:
        parking_layer.show = True
    if ch7 == 1:
        area_layer.show = True

    area_layer.add_to(map1)
    bus_layer.add_to(map1)
    bus_stop_layer.add_to(map1)
    shop_layer.add_to(map1)
    restaurant_layer.add_to(map1)
    parking_layer.add_to(map1)
    cinema_layer.add_to(map1)
    user_results_layer.add_to(map1)
    results_layer.add_to(map1)

    folium.LayerControl().add_to(map1)

    return map1.get_root().render()
コード例 #15
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)
コード例 #16
0
ファイル: app.py プロジェクト: Chrisss09/Travel-Tracker
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv('SECRET_KEY')
app.config["MONGO_DBNAME"] = 'travel_tracker'
app.config["MONGO_URI"] = os.getenv('MONGO_URI')

mongo = PyMongo(app)
countries = mongo.db.country_post.find()

# Generated map
map_obj = folium.Map([45, 3], zoom_start=4, tiles="cartodbpositron")

# Locates current location
plugins.LocateControl().add_to(map_obj)

# Measure distance of points
map_obj.add_child(MeasureControl())

# Create a full screen map
plugins.Fullscreen(position='topright',
                   title='Expand me',
                   title_cancel='Exit me',
                   force_separate_button=True).add_to(map_obj)

# Adding data to map
fgc = folium.FeatureGroup(name="Top 10 countries to visit")
fgr = folium.FeatureGroup(name="Top 10 restaurants of the world")
fga = folium.FeatureGroup(name="Top 10 attractions in the world")
コード例 #17
0
            'Establecimiento Sin Atención Covid-19',
            [['Nombre', 'nombre_establecimiento'], ['Tipo', 'tipo'],
             ['Nivel', 'nivel'], ['Subsector', 'subsector'],
             ['Dependencia', 'dependencia'], ['Número', 'numero_contacto']],
            '#c9d7bf', 7)
draw_points(pd.read_csv('data/farmacias.csv'), 'Farmacia',
            [['Nombre', 'nombre_farmacia'], ['Número', 'numero_contacto']],
            '#b8a7ea', 6)
draw_points(pd.read_csv('data/laboratorios.csv'), 'Laboratorio',
            [['Nombre', 'nombre_laboratorio'], ['Subsector', 'subsector'],
             ['Número', 'numero_contacto'], ['Método de Prueba', 'metodo']],
            '#b7e0dc', 7)
draw_points(pd.read_csv('data/medicina_tradicional.csv'),
            'Medicina Tradicional',
            [['Nombre', 'nombre_proveedor'], ['Número', 'numero_contacto']],
            '#d1a0bd', 6)

plugins.LocateControl(
    drawCircle=False,
    drawMarker=False,
    setView='once',
    initialZoomLevel=17,
    strings={
        'title': 'Ir a mi ubicación',
        'popup': "Estás a {distance} metros de este punto"
    },
).add_to(folium_map)

plugins.FloatImage('leyenda.png', bottom=2, left=2).add_to(folium_map)

folium_map.save('docs/index.html')
コード例 #18
0
ファイル: map.py プロジェクト: Alessandra-m/map
               name='Krasnodar',
               control=False,
               style_function=lambda feature: {
                   "fillColor": "#ffff00",
                   "color": "black",
                   "weight": 1.5,
                   "dashArray": "4, 4"
               }).add_to(m)

#Поисковик
with open('searcher.json', 'r', encoding='utf-8') as f:
    FC = json.load(f)

geojson_obj = folium.GeoJson(FC, name="Poisk", show=False).add_to(m)

plugins.Search(
    geojson_obj,
    position='topleft',
    search_zoom=17,
    search_label='name',
    geom_type='Point',
).add_to(m)

#Контроль уровней
folium.LayerControl(hideSingleBase=True).add_to(m)
#Геолокация
plugins.LocateControl(auto_start=True, setView=10).add_to(m)

m.save("m.html")
webbrowser.open("m.html")
コード例 #19
0
    zoom_start=16.5
)

geojson_obj = folium.GeoJson(points, name="마커 보기").add_to(m)


for i in points["features"]:
    lati = i["geometry"]["coordinates"][1]
    longti = i["geometry"]["coordinates"][0]
    name = i["properties"]["name"]
    html = Template("""
    {{name}}<br>
    </p>
    """).render(name=name)  # html 형태로 마커 클릭 시 팝업 추가
    popup = folium.Popup(html, max_width=200)
    folium.Marker(location=[lati, longti], popup=popup).add_to(
        m)  # html 형태로 마커 클릭 시 팝업 추가

Search(layer=geojson_obj,
       geom_type='Point',
       placeholder="장소 검색",
       search_label='name',
       search_zoom=17,
       collapsed=False,
       position='topright').add_to(m)  # 장소 검색 기능 추가

plugins.LocateControl().add_to(m)  # gps 기능 추가

def make_html():
    m.save('spot_search.html')