def test_feature_group_sub_group(): m = folium.Map([0., 0.], zoom_start=6) fg = folium.FeatureGroup() m.add_child(fg) g1 = plugins.FeatureGroupSubGroup(fg, 'g1') m.add_child(g1) folium.Marker([1, 1]).add_to(g1) folium.Marker([-1, -1]).add_to(g1) g2 = plugins.FeatureGroupSubGroup(fg, 'g2') folium.Marker([-1, 1]).add_to(g2) folium.Marker([1, -1]).add_to(g2) m.add_child(g2) folium.LayerControl().add_to(m) out = normalize(m._parent.render()) # We verify that imports assert '<script src="https://unpkg.com/[email protected]/dist/leaflet.featuregroup.subgroup.js"></script>' in out # noqa # Verify the script part is okay. tmpl = Template(""" var {{ this.get_name() }} = L.featureGroup.subGroup( {{ this._group.get_name() }} ); {{ this.get_name() }}.addTo({{ this._parent.get_name() }}); """) assert normalize(tmpl.render(this=g1)) in out assert normalize(tmpl.render(this=g2)) in out
def leaflet_map(location = [42, -93], height = '70%', width = '80%', zoom_start = 9, geoDataFrame = None, geo_name = None, geo_tool=None, geo_popup=None, geo_color=None): #Defines the map m = folium.Map( location=location, height = height, width = width, zoom_start = zoom_start ) #Add maps tiles folium.TileLayer(tiles='Stamen Terrain',name="Stamen Terrain").add_to(m) folium.TileLayer(tiles='OpenStreetMap',name="Open Street").add_to(m) if geoDataFrame is not None: #Add features fg = folium.FeatureGroup() m.add_child(fg) g1 = plugins.FeatureGroupSubGroup(fg, geo_name) m.add_child(g1) #plot the stations for i in range(geoDataFrame.shape[0]): x = geoDataFrame['geometry'][i].x y = geoDataFrame['geometry'][i].y td = '%.2f' % geoDataFrame[geo_tool][i] g1.add_child(folium.CircleMarker(location=[y,x], radius=10, popup ='<b>Id: </b>%s'%(str(geoDataFrame[geo_popup][i])), tooltip ='<b>val: </b>%s'%(td), line_color='#3186cc', line_width = 0.5, fill_color= geoDataFrame[geo_color][i], fill_opacity=0.7, fill=True)) folium.LayerControl().add_to(m) return m
def PlotLinesClusters(this_map, Dat, FeatureGrp): #TODO: Write Documentation ''' Parameters ---------- this_map : TYPE DESCRIPTION. Dat : TYPE DESCRIPTION. FeatureGrp : TYPE DESCRIPTION. Returns ------- None. ''' popup_field_list = list(Dat.columns) popup_field_list.remove('geometry') for i, row in Dat.iterrows(): TempGrp = plugins.FeatureGroupSubGroup( FeatureGrp, f"{row.stop_sequence}-{row.stop_name}-{row.direction_id}") this_map.add_child(TempGrp) label = '<br>'.join( [field + ': ' + str(row[field]) for field in popup_field_list]) #https://deparkes.co.uk/2019/02/27/folium-lines-and-markers/ LinePoints = [(tuples[1], tuples[0]) for tuples in list(row.geometry.coords)] folium.PolyLine(LinePoints, color="red", weight=4, opacity=1\ ,popup=folium.Popup(html = label,parse_html=False,max_width='300')).add_to(TempGrp)
def add_points(self, geoDataFrame, name_col, color_col='#2c7fb8', popup_col=None): '''Add a set of points to the leaflet map''' #Creates a group for that layer fg = folium.FeatureGroup() self.m.add_child(fg) g1 = plugins.FeatureGroupSubGroup(fg, name_col) self.m.add_child(g1) #plot the stations for i in range(geoDataFrame.shape[0]): x = geoDataFrame['geometry'][i].x y = geoDataFrame['geometry'][i].y td = '%.2f' % geoDataFrame[name_col][i] g1.add_child( folium.CircleMarker(location=[y, x], radius=10, popup='<b>Id: </b>%s' % (str(geoDataFrame[popup_col][i])), tooltip='<b>val: </b>%s' % (td), line_color='#3186cc', line_width=0.5, fill_color=geoDataFrame[color_col][i], fill_opacity=0.7, fill=True))
def plot_lines_clusters(this_map, dat, feature_grp): ''' Plot stops along a route with a line to the closest rawnav point Parameters ---------- this_map: folium.Map folium base map with feature groups. dat : gpd.GeoDataFrame cleaned data on nearest rawnav point to wmata schedule data where - stops whose ordering does not correspond to the index_loc/ time/ odometer are removed i.e. stops are removed if order does not increase with index_loc or time or distance. - where all stops with closest rawnav point > 100 ft. are removed. feature_grp : folium.plugin.FeatureGroup feature group used for stops with nearest rawnav point. Returns ------- None. ''' popup_field_list = list(dat.columns) popup_field_list.remove('geometry') for i, row in dat.iterrows(): temp_grp = \ plugins.FeatureGroupSubGroup(feature_grp, "{}-{}-{}".format(row.stop_sort_order, row.geo_description, row.pattern)) this_map.add_child(temp_grp) label = '<br>'.join( [field + ': ' + str(row[field]) for field in popup_field_list]) # https://deparkes.co.uk/2019/02/27/folium-lines-and-markers/ line_points = [(tuples[1], tuples[0]) for tuples in list(row.geometry.coords)] folium.PolyLine(line_points, color="red", weight=4, opacity=1 \ , popup=folium.Popup(html=label, parse_html=False, max_width='300')).add_to(temp_grp)
def FlightTracks(m, flight): fg = folium.FeatureGroup(name="Flight Tracks") m.add_child(fg) for ilayer, layer in enumerate(flight): if parser.args.relative: label = "AGL: " + length_label(layer.avg_height) else: label = "MSL: " + length_label(layer.avg_elev) color = getColor() print(label) lg = plugins.FeatureGroupSubGroup(fg, label) m.add_child(lg) folium.PolyLine(locations=layer.path, popup=label, color=color).add_to(lg) for ipath, loc in enumerate(layer.path): if ipath == 0: continue folium.CircleMarker(location=loc, radius=5, weight=8. / ipath, popup=label, color=color).add_to(lg)
def map_html(self, tiltakspunkter, filepath): """ tiltakspunkter er av typen Point og oppgitt i epsg:4326 filepath er der du ønsker .html filen med kart skal havne. """ tiltakspunkter = tiltakspunkter box_tmp = bounding_box(tiltakspunkter) box_center_x = (box_tmp[0] + box_tmp[2]) / 2 box_center_y = (box_tmp[1] + box_tmp[3]) / 2 map_center_lon = box_center_x map_center_lat = box_center_y map = folium.Map(location=[map_center_lat, map_center_lon], zoom_start=9, tiles='Stamen Terrain') tiltaksFeature = FeatureGroup(name='Tiltakspunkter', show=False) marker_cluster = plugins.MarkerCluster(options=dict( zoomToBoundsOnClick=False)).add_to(tiltaksFeature) #feature_tiltak = FeatureGroup(name='tiltakspunkter') tooltip_tiltak = 'Tiltakspunkt' tmp_tiltak = tiltakspunkter['punkt_geom_wkt'] x_list = tmp_tiltak.apply(lambda p: p.x) y_list = tmp_tiltak.apply(lambda p: p.y) for i in range(0, len(x_list)): try: Marker(location=[y_list[i], x_list[i]], popup=tiltakspunkter['punkt_navn'][i], icon=folium.Icon(color='red', icon_color='black', icon='angle-double-down', prefix='fa'), tooltip=tooltip_tiltak).add_to(marker_cluster) except: Marker(location=[y_list[i], x_list[i]], popup='Atter et punkt', icon=folium.Icon(color='red', icon_color='black', icon='angle-double-down', prefix='fa'), tooltip=tooltip_tiltak).add_to(marker_cluster) feature_skipshaler = FeatureGroup(name='skipshaler') try: oljetankskip = plugins.FeatureGroupSubGroup( feature_skipshaler, 'oljetankskip') haler_feat_10 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 10] skipshaler_10_json = haler_feat_10.to_json(default=str) style_skipshaler = lambda x: { 'color': '#4DB6AC', 'weight': 3, 'opacity': 0.1, } haler_olje = folium.features.GeoJson( skipshaler_10_json, style_function=style_skipshaler) haler_olje.add_to(oljetankskip) except: pass try: kjemikalie_produkttankskip = plugins.FeatureGroupSubGroup( feature_skipshaler, 'kjemikalie_produkttankskip') haler_feat_11 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 11] skipshaler_11_json = haler_feat_11.to_json(default=str) style_skipshaler = lambda x: { 'color': '#26A69A', 'weight': 3, 'opacity': 0.1, } haler_kjemi = folium.features.GeoJson( skipshaler_11_json, style_function=style_skipshaler) haler_kjemi.add_to(kjemikalie_produkttankskip) except: pass try: gasstankskip = plugins.FeatureGroupSubGroup( feature_skipshaler, 'gasstankskip') haler_feat_12 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 12] skipshaler_12_json = haler_feat_12.to_json(default=str) style_skipshaler = lambda x: { 'color': '#009688', 'weight': 3, 'opacity': 0.1, } haler_gass = folium.features.GeoJson( skipshaler_12_json, style_function=style_skipshaler) haler_gass.add_to(gasstankskip) except: pass try: bulkskip = plugins.FeatureGroupSubGroup(feature_skipshaler, 'bulkskip') haler_feat_13 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 13] skipshaler_13_json = haler_feat_13.to_json(default=str) style_skipshaler = lambda x: { 'color': '#00897B', 'weight': 3, 'opacity': 0.1, } haler_bulk = folium.features.GeoJson( skipshaler_13_json, style_function=style_skipshaler) haler_bulk.add_to(bulkskip) except: pass try: stykkgods_roro_skip = plugins.FeatureGroupSubGroup( feature_skipshaler, 'stykkgods_roro_skip') haler_feat_14 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 14] skipshaler_14_json = haler_feat_14.to_json(default=str) style_skipshaler = lambda x: { 'color': '#00796B', 'weight': 3, 'opacity': 0.1, } haler_stykkgods = folium.features.GeoJson( skipshaler_14_json, style_function=style_skipshaler) haler_stykkgods.add_to(stykkgods_roro_skip) except: pass try: konteinerskip = plugins.FeatureGroupSubGroup( feature_skipshaler, 'konteinerskip') haler_feat_15 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 15] skipshaler_15_json = haler_feat_15.to_json(default=str) style_skipshaler = lambda x: { 'color': '#00695C', 'weight': 3, 'opacity': 0.1, } haler_konteiner = folium.features.GeoJson( skipshaler_15_json, style_function=style_skipshaler) haler_konteiner.add_to(konteinerskip) except: pass try: passasjerbat = plugins.FeatureGroupSubGroup( feature_skipshaler, 'passasjerbat') haler_feat_16 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 16] skipshaler_16_json = haler_feat_16.to_json(default=str) style_skipshaler = lambda x: { 'color': '#81C784', 'weight': 3, 'opacity': 0.1, } haler_passasjer = folium.features.GeoJson( skipshaler_16_json, style_function=style_skipshaler) haler_passasjer.add_to(passasjerbat) except: pass try: ropax_skip = plugins.FeatureGroupSubGroup(feature_skipshaler, 'ropax_skip') haler_feat_17 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 17] skipshaler_17_json = haler_feat_17.to_json(default=str) style_skipshaler = lambda x: { 'color': '#66BB6A', 'weight': 3, 'opacity': 0.1, } haler_ropax = folium.features.GeoJson( skipshaler_17_json, style_function=style_skipshaler) haler_ropax.add_to(ropax_skip) except: pass try: cruiseskip = plugins.FeatureGroupSubGroup(feature_skipshaler, 'cruiseskip') haler_feat_18 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 18] skipshaler_18_json = haler_feat_18.to_json(default=str) style_skipshaler = lambda x: { 'color': '#4CAF50', 'weight': 3, 'opacity': 0.1, } haler_cruise = folium.features.GeoJson( skipshaler_18_json, style_function=style_skipshaler) haler_cruise.add_to(cruiseskip) except: pass try: offshore_supplyskip = plugins.FeatureGroupSubGroup( feature_skipshaler, 'offshore_supplyskip') haler_feat_19 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 19] skipshaler_19_json = haler_feat_19.to_json(default=str) style_skipshaler = lambda x: { 'color': '#43A047', 'weight': 3, 'opacity': 0.1, } haler_offshore = folium.features.GeoJson( skipshaler_19_json, style_function=style_skipshaler) haler_offshore.add_to(offshore_supplyskip) except: pass try: andre_offshorefartoy = plugins.FeatureGroupSubGroup( feature_skipshaler, 'andre_offshorefartoy') haler_feat_20 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 20] skipshaler_20_json = haler_feat_20.to_json(default=str) style_skipshaler = lambda x: { 'color': '#388E3C', 'weight': 3, 'opacity': 0.1, } haler_andre_offshore = folium.features.GeoJson( skipshaler_20_json, style_function=style_skipshaler) haler_andre_offshore.add_to(andre_offshorefartoy) except: pass try: bronnbat = plugins.FeatureGroupSubGroup(feature_skipshaler, 'bronnbat') haler_feat_21 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 21] skipshaler_21_json = haler_feat_21.to_json(default=str) style_skipshaler = lambda x: { 'color': '#00E676', 'weight': 3, 'opacity': 0.1, } haler_bronn = folium.features.GeoJson( skipshaler_21_json, style_function=style_skipshaler) haler_bronn.add_to(bronnbat) except: pass try: slepefartoy = plugins.FeatureGroupSubGroup(feature_skipshaler, 'slepefartoy') haler_feat_22 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 22] skipshaler_22_json = haler_feat_22.to_json(default=str) style_skipshaler = lambda x: { 'color': '#00C853', 'weight': 3, 'opacity': 0.1, } haler_slepe = folium.features.GeoJson( skipshaler_22_json, style_function=style_skipshaler) haler_slepe.add_to(slepefartoy) except: pass try: andre_servicefartoy = plugins.FeatureGroupSubGroup( feature_skipshaler, 'andre_servicefartoy') haler_feat_23 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 23] skipshaler_23_json = haler_feat_23.to_json(default=str) style_skipshaler = lambda x: { 'color': '#9CCC65', 'weight': 3, 'opacity': 0.1, } haler_andre_service = folium.features.GeoJson( skipshaler_23_json, style_function=style_skipshaler) haler_andre_service.add_to(andre_servicefartoy) except: pass try: fiskefartoy = plugins.FeatureGroupSubGroup(feature_skipshaler, 'fiskefartoy') haler_feat_24 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 24] skipshaler_24_json = haler_feat_24.to_json(default=str) style_skipshaler = lambda x: { 'color': '#7CB342', 'weight': 3, 'opacity': 0.1, } haler_fisk = folium.features.GeoJson( skipshaler_24_json, style_function=style_skipshaler) haler_fisk.add_to(fiskefartoy) except: pass try: annet = plugins.FeatureGroupSubGroup(feature_skipshaler, 'annet') haler_feat_25 = self.total_populasjon[ self.total_populasjon.shiptype_nr == 25] skipshaler_25_json = haler_feat_25.to_json(default=str) style_skipshaler = lambda x: { 'color': '#558B2F', 'weight': 3, 'opacity': 0.1, } haler_annet = folium.features.GeoJson( skipshaler_25_json, style_function=style_skipshaler) haler_annet.add_to(annet) except: pass feature_passlines = FeatureGroup(name='passeringslinjer') passeringslinje_json = self.passline.to_json(default=str) tooltip_passeringslinje = 'Passeringslinje' style_passline = lambda x: { 'color': '#000000', 'weight': 4, 'opacity': 1.0, } folium.features.GeoJson( passeringslinje_json, style_function=style_passline, tooltip=tooltip_passeringslinje).add_to(feature_passlines) #feature_tiltak.add_to(marker_cluster) marker_cluster.add_to(map) feature_passlines.add_to(map) feature_skipshaler.add_to(map) oljetankskip.add_to(map) kjemikalie_produkttankskip.add_to(map) gasstankskip.add_to(map) bulkskip.add_to(map) stykkgods_roro_skip.add_to(map) konteinerskip.add_to(map) passasjerbat.add_to(map) ropax_skip.add_to(map) cruiseskip.add_to(map) offshore_supplyskip.add_to(map) andre_offshorefartoy.add_to(map) bronnbat.add_to(map) slepefartoy.add_to(map) andre_servicefartoy.add_to(map) fiskefartoy.add_to(map) annet.add_to(map) folium.LayerControl(collapsed=False).add_to(map) minimap = plugins.MiniMap() map.add_child(minimap) map.add_child(folium.LatLngPopup()) map.save(filepath)
HeatMap( data = data[['latitude','longitude']], min_opacity=0.2, radius=6, blur=2, gradient={.4: 'lime', .65: 'lime', 1: 'green'}, max_zoom=1, layers='republican', overlay=False ).add_to(all_attacks_layer) m.add_child(all_attacks_layer) # 2nd SECTION --> president_party (heatmap) president_party_layer = FeatureGroup(name='President party', overlay=True, control=True, show=False) republican_layer = plugins.FeatureGroupSubGroup(president_party_layer, '_____ Republican', overlay=True, control=True, show=True) democratic_layer = plugins.FeatureGroupSubGroup(president_party_layer, '_____ Democratic', overlay=True, control=True, show=True) data_republican = data[data['president_party'] == 'Republican'] data_democratic = data[data['president_party'] == 'Democratic'] latitude_longitude_republican = data_republican[['latitude','longitude']] latitude_longitude_democratic = data_democratic[['latitude','longitude']] HeatMap( data = latitude_longitude_republican, min_opacity=0.2, radius=6, blur=2, gradient={.4: 'lime', .65: 'lime', 1: 'blue'}, max_zoom=1, layers='republican', overlay=False ).add_to(republican_layer)
def checkBox(self): self.location = self.lineEdit1.text() c_d = self.location domino = pd.read_csv("./Data/domino_population.csv") pizza_school = pd.read_csv("./Data/pizzaschool_populationComplete.csv") pizza_hut = pd.read_csv("./Data/pizza_hut_address_complete.csv") cluster_df0 = pd.read_csv("./Data/상권cluster별위치2.csv") c_d_r = ''.join(c_d.split()) pizza_hut_input = pizza_hut[pizza_hut['city_district'].str.contains( c_d_r)] pizza_school_input = pizza_school[ pizza_school['city_district'].str.contains(c_d_r)] domino_input = domino[domino['city_district'].str.contains(c_d_r)] state_geo = './Data/TL_SCCO_SIG_WGS84.json' state_apart = './Data/korea_apart_decoded2.csv' state_data = pd.read_csv(state_apart, encoding='utf-8') # Initializing the map: c_d_lat = pizza_school_input['lat'] c_d_lat = c_d_lat[c_d_lat.index[0]] c_d_lng = pizza_school_input['lng'] c_d_lng = c_d_lng[c_d_lng.index[0]] m = folium.Map(location=[c_d_lat, c_d_lng], zoom_start=12) m.choropleth(geo_data=state_geo, name='housing price', data=state_data, columns=['Code', '평당 매매가'], key_on='feature.properties.SIG_CD', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.5, legend_name='평당가격') mcg = folium.plugins.MarkerCluster(control=False) m.add_child(mcg) g0 = plugins.FeatureGroupSubGroup(m, 'k-means cluster') m.add_child(g0) g1 = plugins.FeatureGroupSubGroup(m, "Domino's") m.add_child(g1) g2 = plugins.FeatureGroupSubGroup(m, 'Pizza Hut') m.add_child(g2) g4 = plugins.FeatureGroupSubGroup(m, 'Pizza School') m.add_child(g4) #Circle area_list = [] for n in range(len(cluster_df0)): point1 = cluster_df0['max_lat'][n], cluster_df0['max_lng'][n] point2 = cluster_df0['min_lat'][n], cluster_df0['min_lng'][n] distance = haversine(point1, point2) * 1000 area_list.append(math.pi * (distance / 2)**2) folium.Circle([cluster_df0['lat'][n], cluster_df0['lng'][n]], radius=distance / 2, fill=False, fill_color='#00ff00').add_to(g0) # Domino's for n in domino_input.index: folium.Marker( [domino_input['lat'][n], domino_input['lng'][n]], icon=folium.Icon(color='blue'), #, icon = './Data/도미노피자.png' popup=('도미노피자' + ' ' + domino_input['store'][n])).add_to(g1) # Pizza Hut for n in pizza_hut_input.index: folium.Marker( [pizza_hut_input['lat'][n], pizza_hut_input['lng'][n]], icon=folium.Icon(color='red'), #, icon = './Data/도미노피자.png' popup=('피자헛' + ' ' + pizza_hut_input['store'][n])).add_to(g2) folium.LayerControl(collapsed=False).add_to(m) m.save('./Data/Plugins_9.html') map1 = QWebEngineView() # must be absolute path map1.setUrl( QUrl("C:/Users/user/Documents/Gitspace/PIZZA/Data/Plugins_9.html")) leftlayout.addWidget(map1)
FinDat2.to_excel(writer, "DebugSummaryData", index=True) FinRemoveData.to_excel(writer, "RemovedRows", index=True) NoData_da.to_excel(writer, "NoDataFiles", index=True) WrongBusID_da.to_excel(writer, "IncorrectTagFiles", index=True) writer.save() #5 Plot the Start and End Points #**************************************************************************************************************** this_map = folium.Map(zoom_start=16, tiles='Stamen Terrain') folium.TileLayer('openstreetmap').add_to(this_map) folium.TileLayer('cartodbpositron').add_to(this_map) folium.TileLayer('cartodbdark_matter').add_to(this_map) for key, value in SummaryDataDict.items(): value[['DistanceMi', 'TripSpeed_Tags', 'TripSpeed_RawData' ]] = value[['DistanceMi', 'TripSpeed_Tags', 'TripSpeed_RawData']].applymap(lambda x: round(x, 2)) fg = folium.FeatureGroup(name=key) this_map.add_child(fg) StartGrp = plugins.FeatureGroupSubGroup(fg, f"{key} TripStart") this_map.add_child(StartGrp) EndGrp = plugins.FeatureGroupSubGroup(fg, f"{key} TripEnd") this_map.add_child(EndGrp) PlotTripStart_End(value, StartGrp, EndGrp) SumDat = pd.concat(SummaryDataDict.values()) LatLongs = [[x, y] for x, y in zip(SumDat.StartLat, SumDat.StartLong)] this_map.fit_bounds(LatLongs) folium.LayerControl(collapsed=False).add_to(this_map) this_map.save(os.path.join(path_processed_data, "TripSummary.html"))
map_cctv = folium.Map(location=[35.22323, 128.60946], zoom_start=11, tiles='OpenStreetMap') rfile = open("changwon.json", 'r', encoding='cp949').read() jsonData = json.loads(rfile) folium.GeoJson(jsonData, name='읍면동 구분').add_to(map_cctv) # 4-3-5. 마우스 포지션(위도, 경도) 찾기 기능 # from folium.plugins import MousePosition # MousePosition().add_to(map_cctv) # 4-3-6. 측정도구 기능 # from folium.plugins import MeasureControl # map_pplace.add_child(MeasureControl()) len(data[data['카메라대수'] == 4]) fg = folium.FeatureGroup(name="cctv 전체") # 전체그룹 설정 g1 = plugins.FeatureGroupSubGroup(fg, '교통용 cctv') # 서브그룹 틀 만들기 g2 = plugins.FeatureGroupSubGroup(fg, '비교통용 cctv') map_cctv.add_child(fg) # 서브 그룹 맵에 넣기 map_cctv.add_child(g1) map_cctv.add_child(g2) for i in range(0, len(data_traffic)): folium.Circle([data_traffic["위도"][i], data_traffic["경도"][i]], radius=50, color="#ffc039", fill=True).add_to(g1) for j in range(0, len(data_non_traffic)): folium.Circle([data_non_traffic["위도"][j], data_non_traffic["경도"][j]], radius=50, color="#376091", fill=True).add_to(g2) folium.LayerControl(collapsed=False).add_to(map_cctv) map_cctv.save("map_cctv.html")
from folium.plugins import HeatMap HeatMap(data.tolist()).add_to(map_pplace) # 4-3-5. 마우스 포지션(위도, 경도) 찾기 기능 from folium.plugins import MousePosition MousePosition().add_to(map_pplace) # 4-3-6. 측정도구 기능 from folium.plugins import MeasureControl map_pplace.add_child(MeasureControl()) # 4-3-7. 그림 그리기 기능 (이거 되게 자주 쓰일듯!!!!!!) # export=True 옵션 : 내가 그린 영역을 JSON 파일로 뽑아내줌 # 주의점 : 서브그룹이 많으면 4-3-7에서의 export 기능이 안됨. 직접 돌려보면 알거임. fg = folium.FeatureGroup(name="전체") # 전체그룹 설정 g2 = plugins.FeatureGroupSubGroup(fg, '교통정보수집') g1 = plugins.FeatureGroupSubGroup(fg, '교통단속') # 서브그룹 틀 만들기 from folium.plugins import Draw Draw(export=True).add_to(map_pplace) # 4-3-8. 그룹 만들기 g3 = plugins.FeatureGroupSubGroup(fg, '기타') g4 = plugins.FeatureGroupSubGroup(fg, '생활방범') g5 = plugins.FeatureGroupSubGroup(fg, '쓰레기단속') g6 = plugins.FeatureGroupSubGroup(fg, '어린이보호') g7 = plugins.FeatureGroupSubGroup(fg, '재난재해') map_cctv.add_child(fg) # 서브 그룹 맵에 넣기 map_cctv.add_child(g1) map_cctv.add_child(g2) map_cctv.add_child(g3)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) city = kwargs["city"] observatory_name = kwargs["observatory_name"] try: map_definition = MapDefinition.objects.get( observatory_name=observatory_name, city=city) except ObjectDoesNotExist: raise Http404(f"{city} ou l'observatoire {observatory_name}\ n'existe(nt) pas") # Gets all layers corresponding to a city and its observatory map_content_rows = MapContent.objects.filter( map_layer__map_definition__city=city, map_layer__map_definition__observatory_name=observatory_name)\ .order_by("map_layer__layer_depth") # Gets a dict of all unique layers with their latest timestamp unique_layers = map_content_rows.values("map_layer__layer_name")\ .annotate(latest=Max("timestamp")) # Makes a query containing the latest version of layers combined_queries = MapContent.objects.none() for item in unique_layers: combined_queries = combined_queries | \ MapContent.objects.filter(timestamp=item["latest"]) map_content_rows = combined_queries.order_by("map_layer__layer_depth") # Checks if the query isn't empty, # otherwise it would use unbound values. if map_content_rows.__len__() == 0: raise Http404("Page non trouvée (404)") # Building the map lat = map_content_rows[0].map_layer.map_definition.latitude lon = map_content_rows[0].map_layer.map_definition.longitude geomap = folium.Map(location=[lat, lon], zoom_start=12) # CartoDB is a Black and white map to highlight colors folium.TileLayer('cartodb positron', attr="CartoDB").add_to(geomap) # CyclOSM displays cyclist oriented information like parking, pathways. folium.TileLayer( tiles= 'https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png', attr= '<a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases" title="CyclOSM - Open Bicycle render">CyclOSM</a> | Map data: © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', name="CyclOSM").add_to(geomap) # styles args : https://leafletjs.com/reference-1.6.0.html#path-option styles = [ { 'color': '#000000', "dashArray": "1 10" }, { 'color': '#9BBF85', 'weight': 7 }, #006164, #9BBF85 { 'color': '#B3589A', 'weight': 7 }, ] #B3589A , #DB4325 for map_content in map_content_rows: # Adds a layer to the map geojson = map_content.geojson layer_name = map_content.map_layer.layer_name if map_content.map_layer.layer_type == "BASE": index = 0 # Creates a group to hold all sublayers # will allow toogle/untoggle group = folium.FeatureGroup( name=map_content.map_layer.layer_name) geomap.add_child(group) folium.GeoJson(geojson, name=layer_name, # This lambda function is mandatory to use the # style_function argument. It passes a dict as argument # which contains datas about the layer (like the coordinates) # This dict is stored in the "_" argument, deleting it woult # result in the first argument being overridden by the dict. # styles is a list of dict containing args to set various # styles settings such as thickness, opacity, color... style_function=lambda _, ind=index, style=styles: style[ind])\ .add_to(group) elif map_content.map_layer.layer_type == "SATISFAIT": index = 1 # Add a sub group that will be toggled when the # main group is toggled. Layers are added to subgroups # as long as no new main group is defined. subgroup = plugins.FeatureGroupSubGroup( group, name=map_content.map_layer.layer_name) geomap.add_child(subgroup) folium.GeoJson(geojson, name=layer_name, style_function=lambda _, ind=index, style=styles: style[ind])\ .add_to(subgroup) elif map_content.map_layer.layer_type == "NON SATISFAIT": index = 2 subgroup = plugins.FeatureGroupSubGroup( group, name=map_content.map_layer.layer_name) geomap.add_child(subgroup) folium.GeoJson(geojson, name=layer_name, style_function=lambda _, ind=index, style=styles: style[ind])\ .add_to(subgroup) else: # Raise 404 if the layer isn't set properly raise Http404( f"Il y a un problème avec la couche {map_content.map_layer.layer_name}.\ Veuillez contacter l'administreur.") # This is the Layer filter to enable / disable datas on map folium.LayerControl(hideSingleBase=True).add_to(geomap) # Produce html code to embed on our page root = geomap.get_root() html = root.render() # Hack to prevent Boostrap 3.2 to load, causes style conflict. # PR is on the way to update folium as of 29/06/21 # Deleting the extra bootstrap import solves style conflict. old_bs_link = "https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" html = html.replace(old_bs_link, "") context["html_map"] = html context["map_defn"] = map_definition # Produces a tuple (url-compatible layer name, layer name) for # each layer in the map. context["layers_url"] = [ map_content_rows[i].map_layer.layer_name for i in range(len(map_content_rows)) ] # Hack, hard code for today. context['social'] = {} context['social']['og_title'] = "L'Observatoire du Vélopolitain" context['social'][ 'og_description'] = "Suivez l'avancement du vélo à Nantes Métropole" context['social'][ 'og_image'] = "asso_tn/20210228-210131-9011_velorution-psm-sm.jpg" context['social']['twitter_title'] = context['social']['og_title'] context['social']['twitter_description'] = context['social'][ 'og_description'] context['social']['twitter_image'] = context['social']['og_image'] return context
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)
def addFeatureSubGroup(self, feature_group, parent, show=True): self.feature_groups[feature_group] = plugins.FeatureGroupSubGroup( self.feature_groups[parent], feature_group, show=show) self.map.add_child(self.feature_groups[feature_group])
#print(data) lines = [0] #initialise un tab lines[0] = data #on met le dict dans le tab #print(lines[0]) plugins.Fullscreen( #un bouton pour mettre en plein écran position='topright', title='Agrandir', title_cancel='Quitter le mode pleine écran', force_separate_button=True).add_to(m) groupe = folium.FeatureGroup( name='Pour tout enlever') #Un bouton pour enlever tout m.add_child(groupe) #ajout a la map garitoo = plugins.FeatureGroupSubGroup( groupe, 'Garitoo') #un bouton pour afficher les garitoos m.add_child(garitoo) #ajout a la map garini = plugins.FeatureGroupSubGroup( groupe, 'Garini') #un bouton pour afficher les garinis m.add_child(garini) #ajout a la map match = plugins.FeatureGroupSubGroup( groupe, 'Match') #un bouton pour afficher les matchs m.add_child(match) #ajout a la map i = 0 nb = i nb2 = i while i < len(data["coordonnee"]):
def result_map(self, symptom = None, distance = 0.5): ''' get customer's location and make map Symptom will tokenize as nouns Based on tokenized nouns, it will recommend the most fit hospital for patient ''' custo_loc = self.location() l1, l2, l4 = custo_loc[0].__repr__() , custo_loc[1].__repr__() , custo_loc[2].__repr__() hos_loc = self.search_hosp(l1, l2, l4) m = folium.Map([self.Lat, self.Lon], zoom_start = 20) icon_red = folium.Icon(color='red') folium.Marker((self.Lat, self.Lon), tooltip='My location', icon = icon_red).add_to(m) fg = folium.FeatureGroup(name='groups') m.add_child(fg) korean_med = plugins.FeatureGroupSubGroup(fg, '한의병원') m.add_child(korean_med) dentist = plugins.FeatureGroupSubGroup(fg, '치과') m.add_child(dentist) total = plugins.FeatureGroupSubGroup(fg, '종합병원') m.add_child(total) yoyang = plugins.FeatureGroupSubGroup(fg, '요양병원') m.add_child(yoyang) bogun = plugins.FeatureGroupSubGroup(fg, '보건소') m.add_child(bogun) hospi = plugins.FeatureGroupSubGroup(fg, '의원') m.add_child(hospi) etc = plugins.FeatureGroupSubGroup(fg, '기타') m.add_child(etc) for i in range(len(hos_loc)): if self.get_harversion_distance(self.Lon, self.Lat, float(hos_loc[i][6]), float(hos_loc[i][5])) < distance: if hos_loc[i][2] == '기타' or hos_loc[i][2] == '기타(구급차)': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(etc) if hos_loc[i][2] == '병원': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(hospi) if hos_loc[i][2] == '보건소': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(bogun) if hos_loc[i][2] == '요양병원': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(yoyang) if hos_loc[i][2] == '의원': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(hospi) if hos_loc[i][2] == '종합병원': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(total) if hos_loc[i][2] == '치과병원' or hos_loc[i][2] == '치과의원': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(dentist) if hos_loc[i][2] == '한방병원' or hos_loc[i][2] == '한의원': folium.Marker([hos_loc[i][5], hos_loc[i][6]], tooltip = '병원명 :'\ +hos_loc[i][0] +'/' + '전화번호 : ' + hos_loc[i][1]).add_to(korean_med) folium.LayerControl(collapsed=False).add_to(m) return m
incidents_accident = folium.map.FeatureGroup() latitudes = list(mappa_gdf.LATITUDINE) longitudes = list(mappa_gdf.LONGITUDINE) labels = list(mappa_gdf.Value) comune = list(mappa_gdf.COMUNE) descrizione = list(mappa_gdf.DESCRIZIONE_INTERVENTO) finanz = list(mappa_gdf.IMPORTO_PAGATO) finanzass = list(mappa_gdf.IMPORTO_ASSEGNATO) from folium import plugins #fg = folium.FeatureGroup(name='Lavori mai iniziati') mc = folium.plugins.MarkerCluster(control=False) fg1 = folium.plugins.FeatureGroupSubGroup(mc, name='Works not started yet') fg2 = plugins.FeatureGroupSubGroup(mc, name='Works in progress') fg3 = plugins.FeatureGroupSubGroup(mc, name='Finished works') f_map.add_child(mc) for lat, lng, label, comune, descrizione, finanz, finanzass in zip( latitudes, longitudes, labels, comune, descrizione, finanz, finanzass): html = f"""<div style="font-family:helvetica"> <h3> {descrizione} </h3><br> <b>Where:</b> {comune} <br> <b>Amount allocated:</b> {finanzass} euro<br> <b>Amount paid:</b> {finanz} euro<br> <b> Work progress: {'Works not started yet' if label == 1 else 'Works in progress' if label == 2 else 'Finished works'}</b><br> </div> """ iframe = branca.element.IFrame(html=html, width=300, height=200)
tipos = tipo.unique() # creates map central_coords = 20.96, -5.318236 map = folium.Map(location=central_coords, zoom_start=3) # clustering and grouping by area from folium import plugins mcg = folium.plugins.MarkerCluster(control=False) map.add_child(mcg) commsci = plugins.FeatureGroupSubGroup(mcg, areas[0]) academic = plugins.FeatureGroupSubGroup(mcg, areas[1]) education = plugins.FeatureGroupSubGroup(mcg, areas[2]) art = plugins.FeatureGroupSubGroup(mcg, areas[3]) business = plugins.FeatureGroupSubGroup(mcg, areas[4]) map.add_child(commsci) map.add_child(academic) map.add_child(education) map.add_child(art) map.add_child(business) for i in range(0, len(df.lat)): url = '\"' + df.url[i] + '\"'
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)
map_pplace = folium.Map(location=[35.22323, 128.60946], zoom_start=11, tiles='cartodbpositron') # map_pplace = folium.Map(location=[35.22323, 128.60946], zoom_start=11) rfile_1 = open("changwon.json", 'r', encoding='cp949').read() jsonData_1 = json.loads(rfile_1) rfile_2 = open("sanggwon_all.geojson", 'r', encoding='utf-8').read() jsonData_2 = json.loads(rfile_2) # style_function에서 fillColor 는 안에 색깔, fillOpacity는 투명도, color는 선색깔, weight는 선 두께 folium.GeoJson(jsonData_1, name='창원시', style_function= lambda feature: { 'fillColor': 'blue', 'fillOpacity': 0.3, 'color': 'black', 'weight':1, 'opacity':0.1}).add_to(map_pplace) folium.GeoJson(jsonData_2, name='상권', style_function= lambda feature: { 'fillColor': 'pink', 'fillOpacity': 0.7, 'color': 'black', 'weight':0.5}).add_to(map_pplace) fg = folium.FeatureGroup(name="전체") # 전체그룹 설정 g1 = plugins.FeatureGroupSubGroup(fg, '공영 노상') # 서브그룹 틀 만들기 g2 = plugins.FeatureGroupSubGroup(fg, '공영 노외') # g3 = plugins.FeatureGroupSubGroup(fg, '민영') map_pplace.add_child(fg) # 서브 그룹 맵에 넣기 map_pplace.add_child(g1) map_pplace.add_child(g2) # map_pplace.add_child(g3) d_g_s_lati = data_gong_sang["위도"] d_g_s_long = data_gong_sang["경도"] d_g_o_lati = data_gong_oi["위도"] d_g_o_long = data_gong_oi["경도"] # 원 마커에서 color는 선 색깔, fill은 안에 채울지 말지, fill_color는 안에 채울 색깔 설정 for i in range(0, len(data_gong_sang)): # folium.Circle([d_g_s_lati[i], d_g_s_long[i]], radius=int(rad_gong_sang[i]),