# Requete sur PHOTON pour connaitre les coordonnees spatiales d'une adresse postale add_MAME = "49 Boulevard Preuilly 37000 Tours France" geocoder = Nominatim(user_agent="trainee") geo_MAME = geocoder.geocode(add_MAME, True, 30) # Chargement du fond de carte carte = folium.Map(location=[geo_MAME.latitude, geo_MAME.longitude], zoom_start=13) print(carte) # Ajout d'information sur la carte folium.Marker(location=[geo_MAME.latitude, geo_MAME.longitude]).add_to(carte) print(carte) folium.CircleMarker(location=[geo_MAME.latitude, geo_MAME.longitude], radius=10).add_to(carte) print(carte) # Personnalisation des informations restituées msg = "DataLab 2019, c'est ici ! On s'éclate et nos formateurs sont géniaux !" carte = folium.CircleMarker(location=[geo_MAME.latitude, geo_MAME.longitude], radius=10, popup=msg).add_to(carte) print(carte) # Sauvegarde de la carte au format 'html' import os import webbrowser chemin = os.getcwd() + '/carte_py.html' carte.save(chemin) webbrowser.open('file://' + chemin)
elevs = list(volcanoes.ELEV) def pick_color(val): if val < 1000: return 'green' elif 1000 <= val < 3000: return 'orange' else: return 'red' for lat, lon, elev in zip(lats, lons, elevs): #fgroup.add_child(folium.Marker(location=[lat, lon], popup=str(elev) + ' m', icon=folium.Icon(icon='circle-o', color=pick_color(elev)))) fgroup_v.add_child(folium.CircleMarker(location=[lat, lon], radius=6, popup=str(elev) + ' m', fill_opacity=.8, fill=True, color=pick_color(elev))) data = open('web_map/world.json', 'r', encoding='utf-8-sig') fgroup_p.add_child(folium.GeoJson(data=data.read(), style_function=lambda x: {'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'})) my_map.add_child(fgroup_v) my_map.add_child(fgroup_p) my_map.add_child(folium.LayerControl()) data.close()
# print(df.columns.values) # print(df.head()) # print(df.info()) # print(df.describe()) # print('--') mschool_map = fm.Map(location=[37.55, 126.98], tiles='Stamen Terrain', zoom_start=12) for name, lat, lng in zip(df.학교명, df.위도, df.경도): fm.CircleMarker([lat, lng], radius=5, color='brown', fill=True, fill_color='coral', fill_opacity=0.7, popup=name).add_to(mschool_map) mschool_map.save('./Seoul_Middle_School_locations.html') from sklearn import preprocessing label_encoder = preprocessing.LabelEncoder() onehot_encoder = preprocessing.OneHotEncoder() onehot_location = label_encoder.fit_transform(df['지역']) onehot_code = label_encoder.fit_transform(df['코드']) onehot_type = label_encoder.fit_transform(df['유형']) onehot_day = label_encoder.fit_transform(df['주야'])
print('The geograpical coordinate of Toronto are {}, {}.'.format( latitude, longitude)) # In[18]: map_toronto = folium.Map(location=[latitude, longitude], zoom_start=11) # add markers to map for lat, lng, borough, neighborhood in zip(toronto_geo_df['Latitude'], toronto_geo_df['Longitude'], toronto_geo_df['Borough'], toronto_geo_df['Neighbourhood']): label = '{}, {}'.format(neighborhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker([lat, lng], radius=5, popup=label, color='blue', fill=True, fill_color='#3186cc', fill_opacity=0.7, parse_html=False).add_to(map_toronto) map_toronto # In[ ]: # In[ ]: # In[ ]:
stability = root.attrib['stability'] if (stability): if "Poor" in stability: fill_color = "red" elif "Fair" in stability: fill_color = "orange" elif "Good" in stability: fill_color = "lime" #print(root.attrib) if (slope): if int(slope) >= 35: color = "black" elif int(slope) >= 25: color = "blue" else: color = "green" html = '<b>#' + str( i) + '</b><img src="' + image + '" width=700px;>' popup = folium.Popup(html, max_width=2650) folium.CircleMarker([lat, lng], weight=5, radius=8, color=color, fill_color=fill_color, fill_opacity=0.7, popup=popup, max_width=2600).add_to(m) m.save('cluster.html') print("saved cluster.html")
def plot_alert_system(self, postcode): ''' Get map with corresponding risk level for different postcode area from a sequence of postcodes Parameters ---------- postcode: sequence of str Returns ------- folium.Map can produce picture of map with marks ''' #plot real_time data alert system map lat, long, level = self.get_Risk_Level(postcode, 0.1) tem_DF = pd.DataFrame({'lat': lat, 'long': long}) tem_DF = tem_DF.dropna(how='any') lat = np.array(tem_DF.lat) long = np.array(tem_DF.long) locationlist = np.array((lat, long)).transpose() #the plot code must run in jupyter lab, or it cannot ouput a map coldict = { 0: 'lightgreen', 1: 'green', 2: 'lightblue', 3: 'orange', 4: 'red' } #possible colours are [‘red’, ‘blue’, ‘green’, ‘purple’, ‘orange’, ‘darkred’, #’lightred’, ‘beige’, ‘darkblue’, ‘darkgreen’, ‘cadetblue’, ‘darkpurple’, ‘white’, ‘pink’, ‘lightblue’, ‘lightgreen’, ‘gray’, ‘black’, ‘lightgray’] #set the overview place at beginning to centre of England map = folium.Map(location=[54, -1], zoom_start=6) #plot the different risk level point with corresponding colorful mark for point in range(0, len(locationlist)): if level[point] == 'No Risk': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[0], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'Low Risk': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[1], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'Medium Risk': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[2], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'High Risk': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[3], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'Dangerous': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[4], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) return map
all_DESTINATIONS_df.LAT_DESTINATION) ] crs = {'init': 'epsg:4326'} all_DESTINATIONS_gdf = GeoDataFrame(all_DESTINATIONS_df, crs=crs, geometry=geometry) # save first as geojson file all_DESTINATIONS_gdf.geometry.to_file(filename='all_PATHS_gdf.geojson', driver='GeoJSON') # all_DESTINATIONS_gdf.plot() for idx, row in all_ORIGINS_df.iterrows(): folium.CircleMarker( location=[row["LAT_ORIGIN"], row["LON_ORIGIN"]], # popup=row["deviceid"], radius=0.5, color="blue", # fill=True, # fill_color="black", fill_opacity=0.1).add_to(my_map) for idx, row in all_DESTINATIONS_df.iterrows(): folium.CircleMarker( location=[row["LAT_DESTINATION"], row["LON_DESTINATION"]], # popup=row["deviceid"], radius=0.5, color="red", # fill=True, # fill_color="blue", fill_opacity=0.1).add_to(my_map) my_map.save("clean_matched_route_OD.html")
Height: %s m """ #Volcano Feature Group fgv = folium.FeatureGroup(name="Volcanoes") for x, y, name, elev in zip(volcanoX, volcanoY, volcanoName, volcanoElevation): iframe = folium.IFrame(html=html % (name, name, name, str(elev)), width=200, height=100) #Option 1: CircleMarkers fgv.add_child( folium.CircleMarker(location=[x, y], radius=5, popup=folium.Popup(iframe), weight=1, opacity=10.0, color="black", fill=True, fill_color=elev_color(elev), fill_opacity=.7)) #Option 2: Markers # map.add_child(folium.Marker(location=[x,y], popup=folium.Popup(iframe), # icon=folium.Icon(color=elev_color(elev), icon_color='white', icon='flag'))) #Population Feature Group fgp = folium.FeatureGroup(name="Population") fgp.add_child( folium.GeoJson( data=(open("world.json", 'r', encoding='utf-8-sig').read()), style_function=lambda x: {
return 'green' elif elvation <= 3000: return 'orange' else: return 'red' volcanoes = folium.FeatureGroup(name="Volcanoes") for lt, ln, el, nm in zip(lat, long, elev, name): iframe = folium.IFrame(html=html % (nm, nm, el), width=240, height=64) colour = colour_producer(el) volcanoes.add_child( folium.CircleMarker(location=[lt, ln], radius=8, popup=folium.Popup(iframe), fill_color=colour, color=colour, fill_opacity=0.7)) population = folium.FeatureGroup(name="Population") population.add_child( folium.GeoJson( data=open('population.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 15000000 else 'orange' if 15000000 <= x['properties']['POP2005'] < 30000000 else 'red', 'color': 'blank' }))
folium.Marker([44.796171, 20.437084], popup="The Belgrade Fair. ", tooltip=tooltip5, icon=folium.Icon(color="blue")).add_to(m), folium.Marker([44.786568, 20.427067], popup="Hippodrome / Racecourse ", tooltip=tooltip6, icon=folium.Icon(color="blue")).add_to(m), folium.Marker([44.814877, 20.455335], popup="Best Trading Community in SouthEast Europe.", tooltip=tooltip7, icon=Logo1).add_to(m), folium.CircleMarker(location=[44.770493, 20.469921], radius=30, popup="The Military Academy of the University of Defence.", tooltip=tooltip8, color='#fc5628', fill=True, fill_color='#fc5628').add_to(m), # vis marker folium.Marker(location=[44.829768, 20.433458], tooltip=tooltip9, popup=folium.Popup(max_width=550).add_child( folium.Vega(json.load(open(visData)), width=550, height=250))).add_to(m) # geo marker folium.GeoJson(geoOverlay, tooltip=tooltip10, name='Kosutnjak Forest').add_to(m),
def plot_cvrp_solution_routes( solution: CVRPSolution, route_indices_to_plot: Optional[List[int]] = None, config: Optional[OSRMConfig] = None, ) -> None: """Plot solution routes in a map along the streets Parameters ---------- solution A solution to any solver with the vehicles routes to plot route_indices_to_plot If specified, selects a smaller subset of routes to plot by their indices. This can be useful to reduce the clutter in case of a solution with too many vehicles config OSRM configuration """ config = config or OSRMConfig() # Initialize map centered at the mean of the origins origins_mean = np.mean( [(vehicle.origin.lat, vehicle.origin.lng) for vehicle in solution.vehicles], axis=0, ) m = folium.Map( location=origins_mean, zoom_start=12, tiles="cartodbpositron", ) num_vehicles = len(solution.vehicles) route_indices_to_plot = route_indices_to_plot or range(num_vehicles) vehicles_subset = [solution.vehicles[i] for i in route_indices_to_plot] for i, vehicle in enumerate(vehicles_subset): vehicle_color = MAP_COLORS[i % len(MAP_COLORS)] # Plot origin origin = (vehicle.origin.lat, vehicle.origin.lng) folium.CircleMarker(origin, color="red", radius=3, weight=5).add_to(m) # Plot street outlines wiring = _route_wiring(vehicle.circuit, config) folium.PolyLine(wiring, color=vehicle_color, weight=1.0, popup=f"Vehicle {i}").add_to(m) # Plot the deliveries as regular points for delivery in vehicle.deliveries: folium.Circle( location=(delivery.point.lat, delivery.point.lng), radius=10, fill=True, color=vehicle_color, popup=( f"Vehicle {i} ({delivery.point.lat}, {delivery.point.lng})" ), ).add_to(m) return m
def create_seoul_crime_map(self): #생성한 객체의 변수에 값 할당 self.dr.context = "./saved_data/" self.dr.fname = "police_nomr.csv" police = self.dr.csv_dframe() print(police) self.dr.context = "./data/" self.dr.fname = 'geo_simple.json' seoul_geo = self.dr.json_load() self.dr.context = "./data/" self.dr.fname = "crime_in_seoul.csv" crime = self.dr.csv_dframe() station_names = [] for name in crime["관서명"]: station_names.append("서울" + str(name[:-1] + "경찰서")) station_addrs = [] station_lats = [] # 위도 station_lngs = [] # 경도 gmaps = self.dr.create_gmaps() for name in station_names: t = gmaps.geocode(name, language="ko") station_addrs.append(t[0].get("formatted_address")) t_loc = t[0].get("geometry") # 구글의 컬럼 명 그대로lat, lng -> api station_lats.append(t_loc["location"]["lat"]) station_lngs.append(t_loc["location"]["lng"]) print(name + "--------------->" + t[0].get("formatted_address")) # 기존 코드 self.dr.context = './data/' self.dr.fname = 'police_position.csv' police_pos = self.dr.csv_dframe() police_pos['lat'] = station_lats police_pos['lng'] = station_lngs print(police_pos) col = ['살인 검거', '강도 검거', '강간 검거', '절도 검거', ' 폭력 검거'] tmp = police_pos[col] / police_pos[col].max police_pos['검거'] = np.sum(tmp, axis=1) self.dr.fname = 'geo_simple.json' m = folium.Map(location=[37.5902, 126.982], zoom_start=12, title='Stamen Toner') # 속성값 m.choropleth( geo_data=seoul_geo, name="choropleth", data=tuple(zip(police['구별'], police['범죄'])), #columns=["State", "Unemployment"], key_on="feature.id", fill_color="PuRd", fill_opacity=0.7, line_opacity=0.2, lengend_name="CRIME RATE (%)") for i in police_pos.index: #동그란 이미지 추가 folium.CircleMarker([police_pos['lat'][i], police_pos['lng'][i]], radius=police_pos['검거'][i] * 10, fill_color='#0a0a32').add_to(m) #저장하기 m.save('./saved_data/Seoul_Crime_Map.html')
<br>Type: %s """ map = folium.Map([40, -100], zoom_start=5, tiles="Mapbox Bright") fgv = folium.FeatureGroup(name="Volcanoes") for lt, ln, nam, el, typ in zip(lat, lon, name, elev, type): iframe = folium.IFrame(html=html % (nam, str(el), typ), width=250, height=120) # fgv.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe), # icon=folium.Icon(color=color_producer(typ)))) fgv.add_child( folium.CircleMarker(location=[lt, ln], popup=folium.Popup(iframe), fill_color=color_producer(typ), color='grey', fill_opacity=0.7)) fgp = folium.FeatureGroup(name="Population") fgp.add_child( folium.GeoJson( data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red' })) map.add_child(fgv) map.add_child(fgp)
else: return 'red' map = folium.Map(location=(38.58, -99.09), zoom_start=6, tiles="Stamen Terrain") fgv = folium.FeatureGroup(name='Volcanoes') #add multiple markers for lt, ln, el in zip(lat, lon, elev): #fg.add_child(folium.Marker(location=(lt,ln),popup=str(el)+'m',icon=folium.Icon(color=color_proceduer(el)))) fgv.add_child( folium.CircleMarker(location=(lt, ln), radius=6, popup=str(el) + 'm', fill_color=color_proceduer(el), color='grey', fill_opacity=0.7)) fgp = folium.FeatureGroup(name='Population') fgp.add_child( folium.GeoJson( data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 40000000 else 'red' })) map.add_child(fgv) map.add_child(fgp)
import folium import webbrowser svmap = folium.Map(location=[37, -122], titles="Stamen terrain", zoom_start=11) folium.CircleMarker([37, -122], popup="cisco systems", color="#0F8ABE").add_to(svmap) filepath = 'C:\\temp\\map.html' svmap.save(filepath) webbrowser.open('file://' + filepath)
avriandlanf = folium.LayerControl() layerControl = folium.LayerControl(position="topright") volcanoes_layer = folium.FeatureGroup(name="volcanoes_layer") population_layer = folium.FeatureGroup(name="population_layer") html = """<h4>%s</h4> Height: %d meters""" for lt, ln, el, nm in zip(lat, lon, elev, name): i_frame = folium.IFrame(html=html % (nm, el), width=200, height=100) # You can add marker clusters as well to make it look much nicer. # And make the map smaller on a website! volcanoes_layer.add_child(folium.CircleMarker(location=[lt, ln], popup=folium.Popup(i_frame), radius=6, fill_color=set_colour(el), color=set_colour(el), fill_opacity=1)) population_layer.add_child(folium.GeoJson(data=open("world.json", "r", encoding="utf-8-sig").read(), style_function=lambda x:{"fillColor":"green" if x["properties"]["POP2005"] < 10000000 else "orange" if x["properties"]["POP2005"] < 100000000 else "red"})) world_map.add_child(population_layer) world_map.add_child(volcanoes_layer) world_map.add_child(layerControl) world_map.save("Map1.html")
import folium import pandas as pd import numpy as np dtypes = {'BusID': np.int32, 'LAT': np.float64, 'LON': np.float64, 'Angle': np.float32, 'Speed': np.float32, 'Timestamp': 'str'} big_df = pd.read_csv('../dataset/small_tail.csv', dtype=dtypes, chunksize=1000000) i = 0 mapit = folium.Map(location=[12.9716, 77.5946], zoom_start=12, prefer_canvas=True) bus = [] for df in big_df: for index, row in df.iterrows(): print(row['Timestamp']) time = {"2016-07-01": "#eb4034", "2016-07-02":"#eb9934","2016-07-03":"#e2eb34","2016-07-04":"#68eb34","2016-07-04":"#34ebeb","2016-07-05":"#345ceb","2016-07-06":"#d934eb"} folium.CircleMarker(location=[row['LAT'], row['LON']], color=time[row['Timestamp'].split(" ")[0]], radius=2, weight=2,label=index).add_child(folium.Popup(index)).add_to(mapit) i += 1 mapit.save('small_tail.html')
def weatherAPI(): # create a coordinates variable to be used in the api coordniates = post_code.get() params = { 'postal_code': coordniates, 'country': 'JP', 'key': 'aa48ad88872540c2b629a07581fda25f', } # handle errors in connecting to api try: api_result = requests.get( 'https://api.weatherbit.io/v2.0/forecast/daily?', params) api_output = api_result.json() except Exception as e: api_output = "Error connecting to API, please check your parameters" # create api output variables latitude = api_output['lat'] longitude = api_output['lon'] timezone = api_output['timezone'] city = api_output['city_name'] day_1 = api_output['data'][0] day_2 = api_output['data'][1] day_3 = api_output['data'][2] # create LISTS of results dates = [day_1['datetime'], day_2['datetime'], day_3['datetime']] icons = [ day_1['weather']['icon'], day_2['weather']['icon'], day_3['weather']['icon'] ] dscrpts = [ day_1['weather']['description'], day_2['weather']['description'], day_3['weather']['description'] ] maxtemp = [day_1['max_temp'], day_2['max_temp'], day_3['max_temp']] mintemp = [day_1['min_temp'], day_2['min_temp'], day_3['min_temp']] days = [] # print(dates) # print(days) for dy in dates: values = dy.split('-') # print(values) day, month, year = (int(values[2]), int(values[1]), int(values[0])) new_values = datetime.date(year, month, day) list.append(days, new_values.strftime('%a')) # print(days) # print(timezone) new_maxtemp = [ str(int(maxtemp[0])) + " °", str(int(maxtemp[1])) + " °", str(int(maxtemp[2])) + " °" ] new_mintemp = [ str(int(mintemp[0])) + " °", str(int(mintemp[1])) + " °", str(int(mintemp[2])) + " °" ] #print address location # print(city) #print required values date, day, weather icon, weather description, max temp and min temp t = Texttable() t.add_rows([[ 'Date', 'Day', 'Weather icon', 'Description', 'Max temp', 'Min temp' ], [ dates[0], days[0], icons[0], dscrpts[0], new_maxtemp[0], new_mintemp[0] ], [ dates[1], days[1], icons[1], dscrpts[1], new_maxtemp[1], new_mintemp[1] ], [ dates[2], days[2], icons[2], dscrpts[2], new_maxtemp[2], new_mintemp[2] ]]) address_label = Label(window, text=city + "\n" + "3-day forecast") address_label.grid(row=1, column=0, columnspan=3, pady=(10, 0)) # print(type(icons[0])) #SET FRAME 1 FOR DAY 1 # create frame label frame_1 = LabelFrame(window) #display frame on main window frame_1.grid(row=2, column=0, pady=(10, 0), padx=(10, 0)) # GET THE WEATHER ICON FOR DAY 1 # open day 1 weather icon url_1 = "https://www.weatherbit.io/static/img/icons/" + icons[0] + ".png" u_1 = urlopen(url_1) raw_data_1 = u_1.read() u_1.close() icon_1 = ImageTk.PhotoImage(Image.open(BytesIO(raw_data_1))) #create day 1 weather icon label icon_1_label = Label(frame_1, image=icon_1) #display day 1 weather icon label icon_1_label.grid(row=0, column=0, columnspan=2) # SET DATE FOR DAY 1 # create date label date_1_label = Label(frame_1, text=dates[0], anchor=W) #display date on frame date_1_label.grid(row=1, column=0) # SET DAY FOR DAY 1 # create day label day_1_label = Label(frame_1, text=days[0], anchor=E) #display day on frame day_1_label.grid(row=1, column=1) # SET WEATHER DESCRIPTION FOR DAY 1 # create description label descrption_1_label = Label(frame_1, text=dscrpts[0], anchor=W) #display description on frame descrption_1_label.grid(row=2, column=0, columnspan=2) # SET MAX TEMP OR DAY 1 # create max temp label max_temp_1_label = Label(frame_1, text="max " + new_maxtemp[0], anchor=E) #display max temp on frame max_temp_1_label.grid(row=3, column=0, columnspan=2) # SET MIN TEMP OR DAY 1 # create max temp label min_temp_1_label = Label(frame_1, text="min " + new_mintemp[0], anchor=W) #display max temp on frame min_temp_1_label.grid(row=3, column=2, columnspan=2) #SET FRAME 2 FOR DAY 2 frame_2 = LabelFrame(window) frame_2.grid(row=2, column=1, pady=(10, 0), padx=(10, 0)) # GET THE WEATHER ICON FOR DAY 2 # open day 2 weather icon url_2 = "https://www.weatherbit.io/static/img/icons/" + icons[1] + ".png" u_2 = urlopen(url_2) raw_data_2 = u_2.read() u_2.close() icon_2 = ImageTk.PhotoImage(Image.open(BytesIO(raw_data_2))) # create day 1 weather icon label icon_2_label = Label(frame_2, image=icon_2) # display day 1 weather icon label icon_2_label.grid(row=0, column=0, columnspan=2) # SET DATE FOR DAY 2 # create date label date_2_label = Label(frame_2, text=dates[1], anchor=W) #display date on frame date_2_label.grid(row=1, column=0) # SET DAY FOR DAY 2 # create day label day_2_label = Label(frame_2, text=days[1], anchor=E) #display day on frame day_2_label.grid(row=1, column=1) # SET WEATHER DESCRIPTION FOR DAY 2 # create description label descrption_2_label = Label(frame_2, text=dscrpts[1], anchor=W) #display description on frame descrption_2_label.grid(row=2, column=0, columnspan=2) # SET MAX TEMP OR DAY 2 # create max temp label max_temp_2_label = Label(frame_2, text="max " + new_maxtemp[1], anchor=E) #display max temp on frame max_temp_2_label.grid(row=3, column=0, columnspan=2) # SET MIN TEMP OR DAY 2 # create max temp label min_temp_2_label = Label(frame_2, text="min " + new_mintemp[1], anchor=W) #display max temp on frame min_temp_2_label.grid(row=3, column=2, columnspan=2) #SET FRAME 3 FOR DAY 3 frame_3 = LabelFrame(window) frame_3.grid(row=2, column=2, pady=(10, 0), padx=(10, 10)) # GET THE WEATHER ICON FOR DAY 3 # open day 2 weather icon url_3 = "https://www.weatherbit.io/static/img/icons/" + icons[2] + ".png" u_3 = urlopen(url_3) raw_data_3 = u_3.read() u_3.close() icon_3 = ImageTk.PhotoImage(Image.open(BytesIO(raw_data_2))) # create day 1 weather icon label icon_3_label = Label(frame_3, image=icon_3) # display day 1 weather icon label icon_3_label.grid(row=0, column=0, columnspan=2) # SET DATE FOR DAY 3 # create date label date_3_label = Label(frame_3, text=dates[2], anchor=W) #display date on frame date_3_label.grid(row=1, column=0) # SET DAY FOR DAY 3 # create day label day_3_label = Label(frame_3, text=days[2], anchor=E) #display day on frame day_3_label.grid(row=1, column=1) # SET WEATHER DESCRIPTION FOR DAY 3 # create description label descrption_3_label = Label(frame_3, text=dscrpts[2], anchor=W) #display description on frame descrption_3_label.grid(row=2, column=0, columnspan=2) # SET MAX TEMP OR DAY 3 # create max temp label max_temp_3_label = Label(frame_3, text="max " + new_maxtemp[2], anchor=E) #display max temp on frame max_temp_3_label.grid(row=3, column=0, columnspan=2) # SET MIN TEMP OR DAY 3 # create max temp label min_temp_3_label = Label(frame_3, text="min " + new_mintemp[2], anchor=W) #display max temp on frame min_temp_3_label.grid(row=3, column=2, columnspan=2) #SET FRAME 4 FOR MAP frame_4 = LabelFrame(window) frame_4.grid(row=3, column=0, columnspan=2, pady=(10, 10), padx=(10, 0)) # VISUALISE MAP map1 = folium.Map( location=[latitude, longitude], tiles='cartodbpositron', zoom_start=12, ) lambda row: folium.CircleMarker(location=[latitude, longitude]).add_to(map1 ) # mapWidth, mapHeight = (400,500) # width and height of the displayed iFrame, in pixels # srcdoc = map1._repr_html_() # embed = HTML('<iframe srcdoc="{}" ' # 'style="width: {}px; height: {}px; display:block; width: 50%; margin: 0 auto; ' # 'border: none"></iframe>'.format(srcdoc, mapWidth, mapHeight)) map1.save('1.html') map_label = Label(frame_4, text=webbrowser.open('1.html')) # map_label = Label(frame_4, text=display(embed)) map_label.grid(row=0, column=0, columnspan=2, sticky=W + E) #SET FRAME 5 FOR FREE SPACE frame_5 = LabelFrame(window) frame_5.grid(row=3, column=1, columnspan=2, pady=(10, 10), padx=(0, 10)) def plotGraph(): # Make a data frame bars = [(str(days[0]) + " " + str(dates[0])), (str(days[1]) + " " + str(dates[1])), (str(days[2]) + " " + str(dates[2]))] df = pd.DataFrame({ 'x': bars, 'max_temp': [int(maxtemp[0]), int(maxtemp[0]), int(maxtemp[0])], 'min_temp': [int(mintemp[0]), int(mintemp[1]), int(mintemp[2])] }) # Initialize the figure plt.style.use('seaborn-darkgrid') # create a color palette palette = plt.get_cmap('Set1') # multiple line plot num = 0 for column in df.drop('x', axis=1): num += 1 # Find the right spot on the plot plt.subplot(2, 1, num) # Plot the lineplot plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=1.9, alpha=0.9, label=column) # Same limits for everybody! # plt.xlim(0,100) plt.ylim(-11, 40) # Not ticks everywhere plt.tick_params(axis='both', which='major', labelsize=9, pad=10, colors='black') # plt.tick_params(labelleft='off') # Add title plt.title(column, loc='left', fontsize=10, fontweight=0, color=palette(num)) # general title plt.suptitle(city + "\n3-day Temperature forecast", fontsize=9, fontweight=0, color='black', style='italic', y=0.99) # Axis title plt.text(1, -25, 'Date', fontsize=10) plt.text(-0.30, 40, 'Temperature', fontsize=10, rotation='vertical') plt.show() button_plot = Button(frame_5, text="View Temperature graph", command=plotGraph) button_plot.grid(row=0, column=0, pady=(10, 0), padx=10)
def plot_his_map(self): ''' Get map with corresponding rainfall level for different stations Parameters ---------- None Returns ------- folium.Map can produce picture of map with marks ''' lat, long, level = self.get_spe_date() tem_DF = pd.DataFrame({'lat': lat, 'long': long}) tem_DF = tem_DF.dropna(how='any') lat = np.array(tem_DF.lat) long = np.array(tem_DF.long) locationlist = np.array((lat, long)).transpose() #the plot code must run in jupyter lab, or it cannot ouput a map coldict = {0: 'lightgreen', 1: 'blue', 2: 'orange', 3: 'red'} #possible colours are [‘red’, ‘blue’, ‘green’, ‘purple’, ‘orange’, ‘darkred’, #’lightred’, ‘beige’, ‘darkblue’, ‘darkgreen’, ‘cadetblue’, ‘darkpurple’, ‘white’, ‘pink’, ‘lightblue’, ‘lightgreen’, ‘gray’, ‘black’, ‘lightgray’] #set the overview place at beginning to centre of England map = folium.Map(location=[54, -1], zoom_start=6) #plot the different risk level point with corresponding colorful mark for point in range(0, len(locationlist)): if level[point] == 'Low': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[0], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'Medium': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[1], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'High': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[2], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) elif level[point] == 'Very High': folium.CircleMarker(locationlist[point], color='black', fill_color=coldict[3], fill=True, fill_opacity=0.8, radius=10, icon=folium.Icon(color='red')).add_to(map) return map
def add_point_markers(mapobj, gdf, type): """ add point data onto folium map object :param mapobj: folium map object :param gdf: geopandas dataframe :param type: dataframe type (Police Stations, Clinics, Courts and Shelters) :return: updated folium map object """ colr = {'Clinic': '#ef6548', 'Police Station': '#9ecae1', 'Sexual Offence Court': "#fed976", 'Shelter': '#addd8e'} pt_lyr1 = folium.FeatureGroup(name='Clinic') pt_lyr2 = folium.FeatureGroup(name='Police Station') pt_lyr3 = folium.FeatureGroup(name='Sexual Offence Court') pt_lyr4 = folium.FeatureGroup(name='Shelter') layer = {'Clinic': pt_lyr1, 'Police Station': pt_lyr2, 'Sexual Offence Court': pt_lyr3, 'Shelter': pt_lyr4} icon = {'Clinic': pt_lyr1, 'Police Station': pt_lyr2, 'Sexual Offence Court': pt_lyr3, 'Shelter': pt_lyr4} icon_types = {'Clinic': "hospital", 'Police Station': "shield-alt", 'Sexual Offence Court': "balance-scale", 'Shelter': "hands-helping"} # Create a Folium feature group for this layer, since we will be displaying multiple layers pt_lyr = layer[type] for i, row in gdf.iterrows(): # Append lat and long coordinates to "coords" list long = row.geometry.y lat = row.geometry.x name_tag = row.Name try: tel = str(row.Tel) except: tel = '' if type == "Shelter": if "Shelter" not in name_tag: name_tag = "{} Shelter Tel: {}".format(name_tag, tel) else: name_tag = "{} Tel: {}".format(name_tag, tel) size = 8 label = folium.Popup('{}'.format(name_tag), parse_html=True) alpha=0.9 elif type == "Sexual Offence Court": court_type = row.Type name_tag = "{} {} Tel: {}".format(name_tag, court_type, tel) size = 6 label = folium.Popup('{}'.format(name_tag), parse_html=True) alpha = 1 elif type == "Clinic": size = 6 name_tag = name_tag.replace("Clinic Clinic", "Clinic") name_tag = "{} Tel: {}".format(name_tag, tel) label = folium.Popup('{}'.format(name_tag), parse_html=True) alpha = 1 else: size = 6 name_tag = "{} {} Tel: {}".format(name_tag, type, tel) label = folium.Popup('{}'.format(name_tag), parse_html=True) alpha = 1 folium.CircleMarker(location=[long, lat], popup=label, radius=size, fill=True, fill_color=colr[type], fill_opacity=alpha, color=colr[type]).add_to(pt_lyr) # Add this point layer to the map object mapobj.add_child(pt_lyr) return mapobj
return 'orange' else: return 'red' # for lt, ln, el, name in zip(lat, lon, elev, name): # iframe = folium.IFrame(html=html % (name, name, el), width=600, height=400) # fgv.add_child(folium.CircleMarker(location=[lt, ln], radius = 6, popup=str(el)+" m", # fill_color=color_producer(el), color = 'color_producer(el)', fill_opacity = 0.7)) for lt, ln, el in zip(lat, lon, elev): fgv.add_child( folium.CircleMarker(location=[lt, ln], radius=20, popup="Steez", fill_color=color_producer(el), fill=True, color='grey', fill_opacity=0.7)) #fgv.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe, max_width = 600), icon=folium.Icon(color=color_producer(el)))) # Population fgp = folium.FeatureGroup(name="Population") fgp.add_child( folium.GeoJson( data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'
if elevation < 1000: return "green" elif 1000 <= elevation < 3000: return "orange" else: return "red" map = folium.Map(location=[38, -101], zoom_start=5, tiles="Stamen Terrain") fgVolcanos = folium.FeatureGroup(name="Volcanos") for lt, ln, nam, el in zip(lat, lon, name, elev): fgVolcanos.add_child( folium.CircleMarker(location=[lt, ln], radius=7, popup=str(nam) + ": " + str(el) + "m", fill_color=colorGrade(el), color="black", fill_opacity="0.7")) fgPop = folium.FeatureGroup(name="Country Population") fgPop.add_child( folium.GeoJson( data=open("world.json", "r", encoding="utf-8-sig").read(), style_function=lambda x: { "fillColor": "green" if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 100000000 else 'red' })) map.add_child(fgVolcanos) map.add_child(fgPop)
# In[52]: # Generate map to visualize hotel neighbourhood including shopping stores and Cafeteria hotel_map = folium.Map(location=[latitude, longitude], zoom_start=14) for lat, lng, name, categories, address in zip(university_neighbourhood_df['lat'], university_neighbourhood_df['lng'], university_neighbourhood_df['name'], university_neighbourhood_df['categories'],\ university_neighbourhood_df['address']): label = '{}, {}'.format(name, address) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, popup=label, color='blue', fill=True, fill_color='blue', fill_opacity=0.7, parse_html=False).add_to(hotel_map) hotel_map # Generate map to visualize Park, Restaurant and Cafeteria and how they cluster together # In[54]: # create dataframe of Park, Restaurant and Cafeteria park_neighbourhood_df = pd.concat([df_park, df_Restaurant, df_Cafeteria,], ignore_index=True)
g3 = all_indian.drop(['postalCode', 'name', 'categories', 'id'], 1) kclusters = 5 kmeans = KMeans(n_clusters=kclusters, random_state=0).fit(g3) g2 = all_indian g2.insert(0, 'Cluster Labels', kmeans.labels_) # create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(kclusters) ys = [i + x + (i * x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers to the map markers_colors = [] for lat, lon, cluster in zip(g2['lat'], g2['lng'], g2['Cluster Labels']): label = folium.Popup(' Cluster ' + str(cluster), parse_html=True) folium.CircleMarker([lat, lon], radius=5, popup=label, color=rainbow[cluster - 1], fill=True, fill_color=rainbow[cluster - 1], fill_opacity=0.7).add_to(map_clusters) map_clusters
def rad(people): if people > 500: return 50 elif 300 < people <= 500: return 40 elif 100 < people <= 300: return 30 elif 50 < people <= 100: return 20 elif 25 < people <= 50: return 20 else: return 10 map = folium.Map(location=[56.484680, 84.948197], zoom_start=8) marker_cluster = MarkerCluster().add_to(map) for city, lat, lon, people, mark in zip(city, lat, lon, people, mark): # if color_change(mark) == 'green': folium.CircleMarker(location=[lat, lon], radius=rad(people), popup=(city + ": " + str(people) + " чел., ср. балл=" + str(mark)), fill_color=fadeColor(c1, c2, mark / n), color="gray", fill_opacity=0.9).add_to(marker_cluster) map.save("HtmlMaps\map1.html")
d[item.find_all("td")[1].text] = int(tcases.replace(",", "")) cdata = pandas.read_csv("countries.csv") lat = list(cdata["latitude"]) lon = list(cdata["longitude"]) cnt = list(cdata["name"]) map = folium.Map(location=[21.69, 31.09], zoom_start=3, tiles="Stamen Terrain") fg = folium.FeatureGroup(name="Countries") for lt, ln, ct in zip(lat, lon, cnt): if ct in d.keys(): try: fg.add_child( folium.CircleMarker(location=[lt, ln], popup=str(ct) + "\n" + str(d[ct]), radius=radius_gen(d[ct]), fill_color=color_gen(d[ct]), color="#666666", fill_opacity=0.7)) except: pass map.add_child(fg) map.save("CoronaMap.html")
location_data = pd.read_excel('./files/광주나주위치정보.xlsx') location_data.info() location_data.head() import folium Mt_Naju_Station = [35.014250, 126.717045] map_naju = folium.Map(location=Mt_Naju_Station, zoom_start=11) for i in range(len(location_data)): name = location_data['카카오맵위치명'][i] count = location_data['place'][i] size = int(count) * 2 long = float(location_data['위도'][i]) lat = float(location_data['경도'][i]) folium.CircleMarker((long, lat), radius=size, color='red', popup=name).add_to(map_naju) map_naju from folium.plugins import MarkerCluster locations = [] names = [] for i in range(len(location_data)): data = location_data.iloc[i] locations.append((float(data['위도']), float(data['경도']))) names.append(data['카카오맵위치명']) icon_create_function = """\ function(cluster) {
len(locationlist) linear = cm.LinearColormap(['yellow', 'orange', 'red', 'red'], index=[0, 0.1, 0.5, 1.0]) hmap = folium.Map(location=[40.7484, -73.9857], zoom_start=13) fg = folium.FeatureGroup(name="NYC targets") for point in range(0, len(locationlist)): fg.add_child( folium.CircleMarker( location=locationlist[point], radius=4, fill=True, fill_color=linear(for_map['y_pred'][point]), popup=("{name}<br>" "Category: {category}<br>" "Score: {score}<br>" "Note: {note}").format( name=re.sub(r"[^a-zA-Z0-9_]+", ' ', for_map['TARGETNAME'][point]), score=str(round(for_map['y_pred'][point], 3)), category=for_map['CATEGORYNAME'][point], note=for_map['NOTES'][point]), color=linear(for_map['y_pred'][point]), opacity=0.7, fill_opacity=0.7)) hmap.add_child(fg) hmap.save( os.path.join(outfile1, 'nyc_target_from_Sashi_20180504_modelversion3.html'))
return 'red' map = folium.Map(location=[38.58, -99.09], zoom_start=6, tiles="Mapbox Bright") fg = folium.FeatureGroup(name="My Map") for lt, ln, el in zip(lat, lon, elev): #for coordinates in [[12.85, 77.80],[12.90, 77.58]]: #fg.add_child(folium.Marker(location = [lt, ln], popup = "Hi I am a Marker", icon = folium.Icon(color= 'blue'))) #fg.add_child(folium.Marker(location = [lt, ln], popup = folium.Popup(str(el) + " m" , parse_html=True), icon = folium.Icon(color= color_producer()))) fg.add_child( folium.CircleMarker(location=[lt, ln], radius=6, popup=str(el) + " m", fill_color=color_producer(el), color='grey', fill=True, fill_opacity=0.7)) #fg.add_child(folium.Marker(location = [12.90, 77.58], popup = "Hi I am a Marker", icon = folium.Icon(color= 'blue'))) fg.add_child( folium.GeoJson( data=(open('world.json', 'r', encoding='utf-8-sig').read()))) map.add_child(fg) #map.add_child(folium.Marker(location = [12.85, 77.80], popup = "Hi I am a Marker", icon = folium.Icon(color= 'blue'))) #map.save("Mapbg.html")
def CreaMap(adresse,nom): Courbevoie_map= f.Map(location=[48.8967,2.2567],zoom_start=15) icon_market=f.Icon(icon='shopping-cart', prefix='fa',markerColor='orange') icon_pharmacie=f.Icon(icon='',prefix='fa',marketColor='green') icon_medecin=f.Icon(icon='medkit',prefix='fa') icon_pharmacie=f.Icon(icon='ambulance',prefix='fa',markerColor='green') icon=icon_maison=f.Icon(icon='home',markerColor='red') icon1=f.Icon(marketColor='green') f.Marker([48.8967, 2.2567], popup="Monoprix",tooltip="Monoprix",icon=icon_pharmacie).add_to(Courbevoie_map) iti_sup=f.FeatureGroup(name='Itinéraire Supérette la plus proche') iti=f.FeatureGroup(name='Itinéraire Pharmacie la plus proche') zone_sport=f.FeatureGroup(name='Zone de sport') Courbevoie_map = Market_adresse(adresse,Courbevoie_map) Courbevoie_map = Affichage_client(adresse, Courbevoie_map,icon_maison) #on crée la map #on peut rajouter des marqueurs definis par leur longitude et latitude #On cherche à créer des icon #info-sign #cloud #home #arrow-right #file="communes-93-seine-saint-denis.geojson" #f.GeoJson(file,name="Courbevoie").add_to(Courbevoie_map) #Traiter les données d'un fichier csv pas aboutis car données eronnées #lperi=[] #lperifinale=[] #g=open(r'C:\Users\u\Downloads\BAN_odbl_92026.csv', newline='') #reader=csv.reader(g) #for row in reader: #l=[] #if (row[14]!='lat' and row[15]!="long"): #a=float(row[14]) #b=float(row[15]) #l.append(a) #l.append(b) #lperi.append(tuple(l)) #print(lperi) #for i in range(100): #lperifinale.append(lperi[i]) #f.Polygon(lperifinale, color="blue", weight=7.5, opacity=8).add_to(Courbevoie_map) #Trouver les données de Courbevoie : lcourbevoie=[( 48.906294552742324,2.266398166116926), (48.902283797738605,2.284270341799327), (48.898400020270955,2.271065300760704),(48.896657,2.264661), (48.88688989505178,2.253756950262125), (48.89567616526661,2.2337852355532384), (48.900653602651886,2.2316248960533365), (48.90607328944114,2.2582158432572785), (48.906294552742324,2.266398166116926)] #f.Polygon(lcourbevoie, color="blue", weight=7.5, opacity=8).add_to(Courbevoie_map) #Mettre un bouton #a=f.LayerControl(position='bottomright', collapsed=True,autoZIndex=True).add_to(Courbevoie_map) #a.add_child(name="blabla") tooltip="Clique pour voir ce magasin" #popup1=f.Popup(print("blabla")) #f.Marker([48.90,2.26],popup=f.Popup(max_width=450).add_child(f.Marker([48.95,2.26]).add_to(Courbevoie_map)).add_to(Courbevoie_map)) #le popup ce qui apparait #le tooltip ce qui nous fais cliquer #Pour changer les graphiques de l'affichage #f.raster_layers.TileLayer('Stamen Terrain').add_to(Courbevoie_map) #f.raster_layers.TileLayer('Stamen Toner').add_to(Courbevoie_map) #f.raster_layers.TileLayer('Stamen Watercolor').add_to(Courbevoie_map) #f.raster_layers.TileLayer('CartoDB Positron').add_to(Courbevoie_map) #f.raster_layers.TileLayer('CartoDB Dark_Matter',name="map sombre").add_to(Courbevoie_map) #Le par defaut est le mieux dans notre cas # using ipywidgets # plot location with marker Courbevoie_map = Affichage_supérette(Courbevoie_map) Courbevoie_map = Affichage_pharmacie(Courbevoie_map) iti = Itinéraire_Pharmacie_la_plus_proche(Convertisseur_adresse_gps(adresse),Convertisseur_adresse_gps(Adresse_Pharmacie_la_plus_proche(adresse)),iti) iti_sup= Itinéraire_Supérette_la_plus_proche(Convertisseur_adresse_gps(adresse),Coordonnée_Superette_la_plus_proche(adresse),iti_sup) Courbevoie_map.add_child(iti) Courbevoie_map.add_child(iti_sup) #Affichage Zone de Sport loc=Convertisseur_adresse_gps(adresse) f.CircleMarker(location=loc,tooltip="Zone de sport",radius=300,color='black').add_to(zone_sport) Courbevoie_map.add_child(zone_sport) #On fait afficher les featureGroup all_subgroups = f.FeatureGroup(name='Contour Courbevoie') f.Polygon(lcourbevoie, color="blue", weight=7.5, opacity=8).add_to(all_subgroups) Courbevoie_map.add_child(all_subgroups) # add layer control to map (allows layers to be turned on or off) f.LayerControl(collapsed=False).add_to(Courbevoie_map) #Mesure Control # measure control measure_control = plugins.MeasureControl(position='bottomright', active_color='red', completed_color='red', primary_length_unit='meter') # add measure control to map Courbevoie_map.add_child(measure_control) url = 'courbevoie/templates/courbevoie/maCarteCourbevoie.html' Courbevoie_map.save(url)