return 'green' elif 1000 <= elevation < 3000: return 'orange' else: return 'red' map = folium.Map(location=[37.9, -99], zoom_start=6, tiles="Stamen Terrain") fgv = folium.FeatureGroup(name="Volcanoes") for lt, ln, el in zip(lat, lon, elev): fgv.add_child( folium.CircleMarker(location=[lt, ln], radius=6, popup=folium.Popup(str(el) + " m", parse_html=True), fill_color=color_producer(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'] < 20000000 else 'red' }))
def index(): if flask.request.args.get('date') == None: return flask.render_template('index.html', dates=dates, phenom=m_type, months=month) date = int(flask.request.args.get('date')) month_selected = flask.request.args.get('months') phenom_long = flask.request.args.get('phenom') duration = int(flask.request.args.get('duration')) for key, name in CATEGORIES.iteritems(): if name == phenom_long: phenom = key choosed_month, year = month_selected.split('/') try: start_date = datetime.datetime(int(year), int(choosed_month), date, 00, 00, 00) end_date = datetime.datetime(int(year), int(choosed_month), date, 23, 59, 59) + \ datetime.timedelta(days=duration) except: return flask.render_template('error.html', dates=dates, phenom=m_type, months=month, error='date') # http://stackoverflow.com/questions/12438990/select-records-from-postgres-where-timestamp-is-in-certain-rangsoure if phenom_long == 'temperature': sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CA' or measuretype = 'ST');" % ( start_date, end_date) elif phenom_long == 'humidity': sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CB' or measuretype = 'SH');" % ( start_date, end_date) else: sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and measuretype = '%s';" % ( start_date, end_date, str(phenom)) holice_map = folium.Map(MAP_CENTER, zoom_start=18, tiles=None) folium.TileLayer('OpenStreetMap').add_to(holice_map) folium.TileLayer('MapQuestOpen').add_to(holice_map) # Map.add_children(folium.plugins.ImageOverlay(...)) # ICON_URL = 'static/python.jpg' holice_map.add_children( plugins.ImageOverlay( ICON_URL, [PICTURE_COORS], opacity=0.5, )) # folium.LayerControl().add_to(holice_map) holice_map.add_children(folium.LayerControl()) cur.execute(sql_sensor) # list of sensors [int,int,int], instead of [(int,), (int,), (int,)] sensors = [i[0] for i in cur.fetchall()] multi_iter1 = {} locations, popups = [], [] for sensor_sql in sensors: # print sensor_sql for sensor in SENSOR: # print sensor if sensor[0] == sensor_sql: sensor_start_date = datetime.datetime.strptime( sensor[2], "%Y-%m-%d") sensor_end_date = datetime.datetime.strptime( sensor[3], "%Y-%m-%d %H:%M:%S") start_date_new = start_date end_date_new = end_date # print str(end_date) + ' > ' + str(sensor_start_date) # sensor have to not end measurement before start date and not start measurement after the end of end day if end_date >= sensor_start_date and start_date <= sensor_end_date: # if sensor start measurement after start day, the start day will be replaced by sensor start day # if value of start_date and end_date will be replaced, end of sensor measurement after end_date will not be replaced if sensor_start_date > start_date: #print start_date, sensor_start_date start_date_new = sensor_start_date if sensor_end_date < end_date: #print end_date, sensor_end_date end_date_new = sensor_end_date # + datetime.timedelta(days=duration) sensor_data = {} if phenom_long == 'temperature': sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CA' or measuretype = 'ST') and idsensor = %d;" % ( start_date_new, end_date_new, int(sensor[0])) elif phenom_long == 'humidity': sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CB' or measuretype = 'SH') and idsensor = %d;" % ( start_date_new, end_date_new, int(sensor[0])) else: sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and measuretype = '%s' and idsensor = %d;" % ( start_date_new, end_date_new, str(phenom), int(sensor[0])) print sql_data_sensor cur.execute(sql_data_sensor) # sort tuples by time_pattern sql_data = sorted(list(cur.fetchall()), key=lambda time: time[1]) for row in sql_data: # http://stackoverflow.com/questions/16198606/python-linux-timestamp-to-date-time-and-reverse # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior time_index = int( time.mktime( time.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")) * 1000) # some data do not have measurevalue (83k rows) if row[0]: value = float(row[0]) else: value = 0.0 sensor_data[time_index] = value multi_iter1[sensor[0]] = sensor_data # if there are no data if multi_iter1[sensor[0]]: vis = vincent.Line(multi_iter1[sensor[0]], width=600, height=200) x_axis_str = 'data for sensor (' + str( sensor[0]) + '). Time period: ' + str( start_date_new) + ' to ' + str(end_date_new) vis.axis_titles(x=str(x_axis_str), y=phenom_long) vis._axis_properties(axis='y', title_size=15, title_offset=-10, label_align='right', label_angle=0, color='#000000') vis.scales['x'] = vincent.Scale(name='x', type='time', range='width', domain=vincent.DataRef( data='table', field="data.idx")) vis.scales['y'] = vincent.Scale(name='y', type='linear', range='height', domain=vincent.DataRef( data='table', field="data.val")) vis.to_json('static/vis_%s.json' % sensor[0]) popups.append( folium.Popup(max_width=1900).add_child( folium.Vega(json.load( open('static/vis_%s.json' % sensor[0])), width="100%", height="100%"))) locations.append(sensor[1]) if not locations: return flask.render_template('error.html', dates=dates, phenom=m_type, months=month, error='locations') holice_map.add_children(plugins.MarkerCluster(locations, popups)) holice_map.save('templates/map.html') return flask.render_template('map.html')
def create_markup_map(name: str, df: pd.core.frame.DataFrame): """Place a markup for each point with a valid housing price evaluation and position """ map_ = folium.Map( location=france_location, zoom_start=3, control_scale=True, tiles="openstreetmap", ) mcg = folium.plugins.MarkerCluster(control=False) map_.add_child(mcg) houses = folium.plugins.FeatureGroupSubGroup(mcg, "houses") appartements = folium.plugins.FeatureGroupSubGroup(mcg, "appartements") others = folium.plugins.FeatureGroupSubGroup(mcg, "others") map_.add_child(houses) map_.add_child(appartements) map_.add_child(others) for _, row in df.iterrows(): housing_type = row["Type local"] if housing_type == "Maison": color = "darkgreen" icon = "home" context = houses elif housing_type == "Appartement": color = "red" icon = "pause" context = appartements else: color = "black" icon = "info-sign" context = others price = int(row["Valeur fonciere"]) address = get_address_from_row(row) context.add_child( folium.Marker( (row["lat"], row["lon"]), popup=folium.Popup( f"{housing_type}</br> {address} <b>{price}€</b>", # Not working properly max_width="400px", min_width="200px", ), tooltip=housing_type, icon=folium.Icon(color=color, icon=icon), ) ) map_.add_child( plugins.Fullscreen( position="topright", title="Expand me", title_cancel="Exit me", force_separate_button=True, ) ) map_.add_child(folium.LayerControl(collapsed=False)) map_.add_child(plugins.MeasureControl()) map_.add_child(plugins.MiniMap()) save_map(map_, name)
</td> <td style="width: 99px;"><h6><a href="http://localhost:{P}/current" target="_blank" rel="noopener">Current |</a><a href="http://localhost:{P}/probe" target="_blank" rel="noopener"> Probe</h6></a></td> </tr> <tr> <td style="width: 169px;"> <h4>Total Machines: </td> <td style="width: 99px;"><b>{M}</b></td> </tr> <tr> <td style="width: 169px;"> <h4>Capacity Utilization: </td> <td style="width: 99px;"><b>{C}%</h4></b></td> </tr> </tbody> </table>''', width=300, script=True) if (C == 100): I = 'star' else: I = 'info-sign' popup = folium.Popup(info, max_width=2650) #put custom text whenever the marker of machine clicked on map. folium.Marker(location=[lat[i], lon[i]], icon=folium.Icon(icon=I, color=COL), popup=popup).add_to(mape) #save map in the view html file to be rendered by flask. mape.save("templates/view.html")
map = folium.Map(location=[38.58, -99.09], zoom_start=5, tiles="Stamen Terrain") fgp = folium.FeatureGroup(name="Human 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' })) fgv = folium.FeatureGroup(name="Volcanoes") for lt, ln, el, name in zip(lat, lon, elev, name): iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100) fgv.add_child( folium.CircleMarker(location=[lt, ln], radius=6, popup=folium.Popup(iframe), fill_color=color_producer(el), color='grey', fill_opacity=.7)) map.add_child(fgp) map.add_child(fgv) map.add_child(folium.LayerControl()) map.save("volcanoes_map.html")
break else: continue print("The highest calls due to Fire were %d on %s month" % (max_val, mo_max)) # In[2]: #8 import folium import pandas as pd df = pd.read_csv("mew2ktykm4.csv") d1 = df[df['title'].str.contains('Traffic') == True].head(10) d2 = d1[["addr", "title", "e", "lat", "lng"]] # lon1=list(d2["lng"]) # lat1=list(d2["lat"]) # area=list(d2["addr"]) map = folium.Map(location=[d2['lat'].mean(), d2['lng'].mean()], zoom_start=10) fg = folium.FeatureGroup(name="Traffic Call Area") for lat1, lon1, area in zip(d2['lat'], d2['lng'], d2['addr']): fg.add_child( folium.Marker(location=[lat1, lon1], popup=(folium.Popup(area)), icon_color='green')) map.add_child(fg) map.save(outfile="absmap.html") map # In[ ]: # In[ ]:
import os m = folium.Map(location=[34.1229, 74.8630], zoom_start=12) tooltip = 'Click For More Info' vis = os.path.join('data', 'vis.json') overlay = os.path.join('data', 'overlay.json') # SRINAGAR # Create markers(tourist spots) folium.Marker( [34.1229, 74.8630], popup=folium.Popup( '<a href="https://www.beautifulworld.com/asia/india/dal-lake/" target="blank"><strong>Dal Lake</strong></a>' ), icon=folium.Icon(icon='star'), tooltip=tooltip).add_to(m), folium.Marker( [34.1229, 74.8794], popup=folium.Popup( '<a href="https://www.tourmyindia.com/states/jammu-kashmir/nishant-garden.html" target="blank"><strong>Nishat Bagh</strong></a>' ), icon=folium.Icon(icon='star'), tooltip=tooltip).add_to(m), folium.Marker( [34.1485, 74.8696], popup=folium.Popup( '<a href="https://www.tourmyindia.com/states/jammu-kashmir/shalimar-garden.html" target="blank"><strong>Shalimar Bagh</strong></a>' ),
def grid_plot(self, boundaries, colors, legend=True): """Function to plot the probability grid and determine the color of each square based on probability Args: -boundaries(list): The boundaries determining the color of each square. The first and last element be 0 and 1 respectively and all elements must be strictly increasing -colors(list): The length must the be equal to the length of the boundaries list - 1 -legend(boolean): Whether to include a legend the default is true The boundary from the ith to the i+1 index in the boundaries list maps to the ith color in the colors list. Hence the requirements on the lengths Returns: The map with the probability grid superimposed """ # Checking if the arguments are of a valid length self.bound_col_checks(boundaries=boundaries, colors=colors) north = self.north south = self.south east = self.east west = self.west gmm = self.gmm grid_df = self.grid_df() grid_perc_array = np.array(grid_df['probability']) # Code to find the color for each square based on probability color_array = [] for grid_perc in grid_perc_array: for bound_idx in range(len(boundaries) - 1, -1, -1): boundary = boundaries[bound_idx] if grid_perc >= boundary: color_array.append(colors[bound_idx]) break # Defining a geojson grid and plotting it on a map geojson_grid = self.get_geojson_grid(upper_right=(north, east), lower_left=(south, west), n=self.squares) for idx, box in enumerate(geojson_grid): geo_json = json.dumps(box) color = color_array[idx] popup = folium.Popup(grid_perc_array[idx]) grid_square = folium.GeoJson( geo_json, style_function=lambda feature, color=color: { 'fillColor': color, 'color': "black", 'weight': 2, 'dashArray': '5, 5', 'fillOpacity': 0.55, }) grid_square.add_child(popup) mp = self.mp mp.add_child(grid_square) if legend == True: mp = self.legend_maker(mp=mp, boundaries=boundaries, colors=colors) return mp
import folium import os m = folium.Map(location=[31.0979, 77.2678], zoom_start=11) tooltip = 'Click For More Info' vis = os.path.join('data', 'vis.json') overlay = os.path.join('data', 'overlay.json') # SHIMLA # Create markers(tourist spots) folium.Marker( [31.0979, 77.2678], popup=folium.Popup( '<a href="map.html" target="blank"><strong>Kufri</strong></a>'), icon=folium.Icon(icon='star'), tooltip=tooltip).add_to(m), folium.Marker( [31.2249, 77.3569], popup=folium.Popup( '<a href="map.html" target="blank"><strong>Chadwick Falls</strong></a>' ), icon=folium.Icon(icon='star'), tooltip=tooltip).add_to(m), folium.Marker( [31.1196, 77.1389], popup=folium.Popup( '<a href="map.html" target="blank"><strong>Mall Road</strong></a>'), icon=folium.Icon(icon='star'), tooltip=tooltip).add_to(m),
def run(self): try: progressBarStep = 68 * 1000 / ( self.data['grid']['VERTICAL_CELLS'] * self.data['grid']['HORIZONTAL_CELLS']) self.update_progresslabel.emit("Построение сети") grid = self.data['grid']['geojson'] map = folium.Map(location=self.data['start'], max_bounds=True, zoom_start=6, max_zoom=6, zoom_control=False, scrollWheelZoom=False) map.add_child( folium.GeoJson(data=self.data['contour'], style_function=lambda x: { 'color': 'black', 'fillColor': 'transparent' })) self.update_progresslabel.emit("Картрирование") pokazetel = "prediction" # max_temp = -1000.0 # for k in self.data['map'].keys(): # if (self.data['map'][k][pokazetel] > max_temp): # max_temp = self.data['map'][k][pokazetel] for i, geo_json in enumerate(grid): self.update_progressbar.emit(progressBarStep) i_to_row = (self.data['grid']['VERTICAL_CELLS'] - 1) - i % self.data['grid']['VERTICAL_CELLS'] i_to_column = i // self.data['grid']['VERTICAL_CELLS'] v = self.data['map'][i_to_row, i_to_column][pokazetel] if v < 0.5: color = mpl.colors.to_hex('#00ff00') elif v >= 0.5 and v < 0.8: color = mpl.colors.to_hex('yellow') elif v >= 0.8 and v < 0.92: color = mpl.colors.to_hex('orange') else: color = mpl.colors.to_hex('red') #color = plt.cm.Reds(self.data['map'][i_to_row, i_to_column][pokazetel] / max_temp) border_color = 'black' if np.isnan(self.data['map'][i_to_row, i_to_column][pokazetel]): continue gj = folium.GeoJson( geo_json, style_function=lambda feature, color=color: { 'fillColor': color, 'color': border_color, 'weight': 0.5, 'fillOpacity': 0.75, }) popup = folium.Popup( str(i_to_row) + " " + str(i_to_column) + " " + str(self.data['map'][i_to_row, i_to_column][pokazetel])) gj.add_child(popup) map.add_child(gj) map.save('./maps/map.html') self.update_mapsignal.emit('./maps/map.html') except: pass self.longtask_finished.emit()
#Build basemap over New York City def generateBaseMap(default_location=[40.7128, -74.0060], default_zoom_start=12): base_map = folium.Map(location=default_location, tiles="Stamen Terrain", control_scale=True, zoom_start=default_zoom_start) return base_map #Generate BaseMap base_map = generateBaseMap() #Integrate Airbnb data for i in zip(range(0, len(const1))): airbnb_brand = "#FF5A5F" label = "Potential revenue: $" + str( format(const1.iloc[i]["airbnb_potential_revenue"], ",.0f")) #print(label) folium.Circle( location=[const1.iloc[i]['latitude'], const1.iloc[i]['longitude']], radius=const1.iloc[i]['airbnb_potential_revenue'] / 60, fill=True, fill_color=airbnb_brand, color=airbnb_brand, fill_opacity=0.5, ).add_child(folium.Popup(label)).add_to(base_map) #Save map base_map.save("airbnb_potential_revenue_NYCmap.html")
#Now just add the random value to each column result['Lat'] = result['Lat'] + result['RANDlat'] result['Lon'] = result['Lon'] + result['RANDlon'] # Now the points have been jittered # Establish the mean coordinates for where to start your map Mean_coords = (42.959443, -85.742777) # Creates your map map = folium.Map(location=Mean_coords, zoom_start=6) #getting the points to appear clustered at the different scales marker_cluster = folium.plugins.MarkerCluster().add_to(map) #Adding the points and popup windows onto the map # for full details on this for loop look at the lab instructions for i in range(0, len(result)): folium.Marker( [result.iloc[i]['Lat'], result.iloc[i]['Lon']], popup=folium.Popup( '<b>Job Title: </b>' + result.iloc[i]['job_title'] + '<br>' + '<b>Company: </b>' + result.iloc[i]['company_name'] + '<br>' + '<b>Location: </b>' + result.iloc[i]['location'] + '<br>' + '<b> Salary: </b>' + result.iloc[i]['salary'] + '<br>' + '<b>Summary: </b>' + result.iloc[i]['summary'], max_width=450), icon=folium.Icon(color='red')).add_to(marker_cluster) #saving the map as an html file map.save(outfile='map.html')
return 'green' elif 1000 > Elevation <= 2000: return 'blue' elif 2000 > Elevation <= 3000: return 'orange' else: return 'red' fg = folium.FeatureGroup(name="Volcanoes") for lt, ln, el in zip(lat, lon, elev): fg.add_child( folium.CircleMarker(location=[lt, ln], radius=6, popup=folium.Popup("Elevation " + str(el) + " m", parse_html=True), fill=True, fill_color=clor(el), color='grey', fill_opacity=1.0)) 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': 'yellow' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red' }))
def mapping_df(full_ser, prueba): """ Recibe un Dataframe con Coordenadas y lo grafica en un mapa. retorna un html para usar con Iframe. Prueba es el tipo de prueba, Serologia o PCR """ df = table_prueba(full_ser, prueba) print(df.head()) #Mapa: import folium folium_hmap = folium.Figure(width=500, height=500) m = folium.Map( location=[8.3344713, -75.6666238], width='100%', height='100%', zoom_start=8, #Por defecto es 10 tiles="OpenStreetMap" #OpenSteetMap ,Stamen Toner(Terrain, Watercolor) ).add_to(folium_hmap) data = df if prueba == 'Serologia': for i in range(0, len(data)): html = f""" <head> <link rel="stylesheet" href="https://codepen.io/chriddyp/pen/dZVMbK.css"> <head> <h6> {data.iloc[i]['MUNICIPIO']}</h6> <p> Serología: </p> <p>Positivas: {data.iloc[i]['POSITIVOS SEROLOGIA']}</p> <p> Total: {data.iloc[i]['No DE PRUEBAS SEROLOGIA']}</p> """ iframe = folium.IFrame(html=html, width=130, height=160) popup = folium.Popup(iframe, max_width=2650) folium.Circle( location=[data.iloc[i]['lat'], data.iloc[i]['lon']], popup=popup, radius=float(data.iloc[i]['No DE PRUEBAS SEROLOGIA']) * 100, color='lightgray', fill=True, fill_color='gray').add_to(m) for i in range(0, len(data)): html = f""" <head> <link rel="stylesheet" href="https://codepen.io/chriddyp/pen/dZVMbK.css"> <head> <h6> {data.iloc[i]['MUNICIPIO']}</h6> <p> Serología: </p> <p>Positivas: {data.iloc[i]['POSITIVOS SEROLOGIA']}</p> <p> Total: {data.iloc[i]['No DE PRUEBAS SEROLOGIA']}</p> """ iframe = folium.IFrame(html=html, width=130, height=160) popup = folium.Popup(iframe, max_width=2650) folium.Circle(location=[data.iloc[i]['lat'], data.iloc[i]['lon']], popup=popup, radius=float(data.iloc[i]['POSITIVOS SEROLOGIA']) * 100, color='cadetblue', fill=True, fill_color='blue').add_to(m) folium_hmap.save('prueba_por_municipios.html') else: for i in range(0, len(data)): html = f""" <head> <link rel="stylesheet" href="https://codepen.io/chriddyp/pen/dZVMbK.css"> <head> <h6> {data.iloc[i]['MUNICIPIO']}</h6> <p> PCR: </p> <p>Positivas: {data.iloc[i]['POSITIVOS PCR']}</p> <p> Total: {data.iloc[i]['No DE PRUEBAS PCR']}</p> """ iframe = folium.IFrame(html=html, width=130, height=160) popup = folium.Popup(iframe, max_width=2650) folium.Circle(location=[data.iloc[i]['lat'], data.iloc[i]['lon']], popup=popup, radius=float(data.iloc[i]['No DE PRUEBAS PCR']) * 100, color='lightgray', fill=True, fill_color='lightgray').add_to(m) for i in range(0, len(data)): #redundante html = f""" <head> <link rel="stylesheet" href="https://codepen.io/chriddyp/pen/dZVMbK.css"> <head> <h6> {data.iloc[i]['MUNICIPIO']}</h6> <p> PCR: </p> <p>Positivas: {data.iloc[i]['POSITIVOS PCR']}</p> <p> Total: {data.iloc[i]['No DE PRUEBAS PCR']}</p> """ iframe = folium.IFrame(html=html, width=130, height=160) popup = folium.Popup(iframe, max_width=2650) folium.Circle(location=[data.iloc[i]['lat'], data.iloc[i]['lon']], popup=popup, radius=float(data.iloc[i]['POSITIVOS PCR']) * 100, color='crimson', fill=True, fill_color='crimson').add_to(m) folium_hmap.save('prueba_por_municipios.html') return folium_hmap
import folium import pandas data = pandas.read_csv("Volcanoes.txt") lat = list(data["LAT"]) lon = list(data["LON"]) elev = list(data["ELEV"]) html = """<h4>Volcano information:</h4> Height: %s m """ map = folium.Map(location=[38.58, -99.09], zoom_start=5, tiles="Mapbox Bright") fg = folium.FeatureGroup(name = "My Map") for lt, ln, el in zip(lat, lon, elev): iframe = folium.IFrame(html=html % str(el), width=200, height=100) fg.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe), icon = folium.Icon(color = "green"))) map.add_child(fg) map.save("Map_html_popup_simple.html")
import webbrowser import folium file1 = open("web_map\\data\\coordinates.txt", "r") coordinates=file1.readlines() file1.close() file2 = open("web_map\\data\\places.txt", "r", encoding="utf-8") places=file2.readlines() file2.close() html = """ <a href="https://www.google.com/search?q=%s" target="_blank">%s</a> """ fg = folium.FeatureGroup(name="My places") map = folium.Map(location=[52, 21], zoom_start=8) for pl, cor in zip(places, coordinates): wsp=cor.split(",") iframe = folium.IFrame(html=html % (pl, pl), width=75, height=35) fg.add_child(folium.Marker(location=[wsp[0], wsp[1]], zoom_start=4, color="red", popup=folium.Popup( iframe))) map.add_child(fg) map.save("web_map\\html\\moje_miejsca_offline.html") webbrowser.open("web_map\\html\\moje_miejsca_offline.html")
return 'red' else: return 'lightred' stream = os.popen('./locateme -f "{LAT},{LON}"') output = stream.read() segments = output.split(',') g = geocoder.ip('me') map = folium.Map(location=segments, zoom_start=14, tiles="OpenStreetMap") hi = "Hi! You are currently at %s, %s!" % (g.city, g.state) f = folium.FeatureGroup(name="My Map") f.add_child( folium.Marker(location=segments, popup=folium.Popup(hi), icon=folium.Icon('blue'))) api_key = '9Muq5wcq6bVdiblfSgNeisll3VZI6AUkZ_odZnUUqP1BDqqLjjfXEQhfdvYX_lKC5Wy_GweFkV_nT22zgg9bdQ4qLj9j3F3_z_qKAPErJz1dODmHI-vqemtt-EEeX3Yx' #business_id = 'JHU5HF1aEDkdwIWf2D765A' header = {'Authorization': 'bearer %s' % api_key} endpoint = 'https://api.yelp.com/v3/businesses/search' param = { 'term': input("search for: "), 'limit': 50, 'radius': 20000, 'location': "%s, %s" % (g.city, g.state) } response = req.get(url=endpoint, params=param, headers=header) #convert JSON string to a Dictionary
import folium import pandas import base64 data = pandas.read_csv("doctors.txt") lat = list(data["LAT"]) lon = list(data["LON"]) map = folium.Map([43.6532, -79.3832], zoom_start=10, tiles="Stamen Terrain") encoded = base64.b64encode(open('sign1.jpg', 'rb').read()).decode() html = '<img src="data:image/jpeg;base64,{}">'.format iframe = folium.IFrame(html(encoded), width=632 + 20, height=420 + 20) popup = folium.Popup(iframe, max_width=2650) fgv = folium.FeatureGroup(name="Clinics") for lt, ln in zip(lat, lon): fgv.add_child( folium.CircleMarker(location=[lt, ln], radius=6, popup=popup, color='red', fill=True, fill_opacity=0.7)) map.add_child(fgv) map.save("Map.html")
def map_results_raster(structure_list, raster, breach=None, book=None, width=800, height=700, zoom = 14): from folium import raster_layers colormap=lambda x: (0, 0, 0, x) overtopped={} # Read in Raster Data src = gdal.Open(raster) ulx, xres, xskew, uly, yskew, yres = src.GetGeoTransform() lrx = ulx + (src.RasterXSize * xres) lry = uly + (src.RasterYSize * yres) centerx, centery = np.mean([ulx, lrx]),np.mean([uly, lry]) img = src.ReadAsArray() colormap=lambda x: (0, 1, 1, x) folmap = Map(width=800, height=700, location=[centery, centerx], zoom_start=zoom) folmap.add_child(raster_layers.ImageOverlay(img, colormap=colormap,opacity=0.5, bounds =[[lry, lrx],[uly, ulx]], mercator_project=True)) if isinstance(breach, gpd.geodataframe.GeoDataFrame): if breach.crs != '4326': breach = breach.to_crs({'init' :'epsg:4326'}) html = f"""<h4>Breach Location</h4>""" iframe=branca.element.IFrame(html=html, width=120, height=80) popup = folium.Popup(iframe) folmap.add_child(folium.CircleMarker(location=[breach.loc[0, 'geometry'].y, breach.loc[0, 'geometry'].x], popup= popup,radius=6, weight=12, color='Red')) if isinstance(book, gpd.geodataframe.GeoDataFrame): print('Book!', book.crs) if book.crs != {'init': 'epsg:4326'}: print('Projecting') book = book.to_crs({'init' :'epsg:4326'}) # Placeholder for plotting structures for structures in structure_list: #print(structures.crs) if structures.crs != '4326': structures = structures.to_crs({'init' :'epsg:4326'}) try: for idx in structures.index: sID = structures.loc[idx, 'ID'] sWSE = round(structures.loc[idx, 'Max WSE'],2) sCrest = round(structures.loc[idx, 'Crest'],2) sStation = int(structures.loc[idx, 'Station']) if sWSE < sCrest: html = f"""<h4>{sID}</h4><p>Station {sStation}</p><p>Levee Crest {sCrest}</p><p>Max WSE {sWSE}</p>""" iframe=branca.element.IFrame(html=html, width=200, height=150) popup = folium.Popup(iframe) folmap.add_child(folium.CircleMarker(location=[structures.loc[idx, 'geometry'].y, structures.loc[idx, 'geometry'].x], popup= popup,radius=3, weight=3, color='black')) else: max_depth=round(sWSE-sCrest,2) overtopped[f'{sID} Station {sStation}'] = max_depth html = f"""<h4>{sID}</h4><p>Station {sStation}</p><p>Levee Crest {sCrest}</p><p>Max WSE {sWSE}</p><p>Max Overtopping Depth {max_depth}</p>""" iframe=branca.element.IFrame(html=html, width=200, height=250) popup = folium.Popup(iframe) folmap.add_child(folium.CircleMarker(location=[structures.loc[idx, 'geometry'].y, structures.loc[idx, 'geometry'].x], popup= popup,radius=4, weight=4, color='red')) line_points = zip(structures.geometry.y.values,structures.geometry.x.values) folium.PolyLine(list(line_points), color='black').add_to(folmap) except: print('ERROR') add_tiles(folmap) return folmap, overtopped
import pandas as pd def color_producer(elevation): if elevation < 1000: return 'green' elif 1000 <= elevation < 3000: return 'orange' else: return 'red' data = pd.read_csv('Volcanoes.txt') data_list = zip(list(data['LAT']), list(data['LON']), list(data['ELEV'])) map = folium.Map(location=[38.58, -99.09], tiles='OpenStreetMap') fgv = folium.FeatureGroup(name='Volcanoes') for lt, ln, el in data_list: # fg.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(str(el) + ' m', parse_html=True, max_width=50), icon=folium.Icon(color=color_producer(el)))) fgv.add_child(folium.CircleMarker(location=[lt, ln], radius=6, popup=folium.Popup(str(el) + ' m', parse_html=True, max_width=50), fill_color=color_producer(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'] < 20000000 else 'red' })) map.add_child(fgv) map.add_child(fgp) map.add_child(folium.LayerControl()) map.save('Map1.html')
import folium import pandas voldata = pandas.read_csv("Volcanoes_USA.txt") def elevcolor(elev): if elev < 1000: return 'green' elif 1000 <= elev < 3000: return 'orange' else: return 'red' map1 = folium.Map(location=[38.58, -99.09], zoom_start=6, tiles="Mapbox Bright") fg1 = folium.FeatureGroup(name="My Map") for lt, ln, name, loc, elv in zip(voldata.LAT, voldata.LON, voldata.NAME, voldata.LOCATION, voldata.ELEV): fg1.add_child( folium.Marker(location=[lt, ln], popup=folium.Popup(name + " " + loc, parse_html=True), icon=folium.Icon(elevcolor(elv)))) map1.add_child(fg1) map1.save("map2.html")
""" def color_producer(elevation): if elevation < 1000: return 'green' elif 1000 <= elevation < 3000: return 'orange' else: return 'red' map = folium.Map(location=[38.58, -99.09],zoom_start=6,tiles = "Stamen Terrain") fgv = folium.FeatureGroup(name="Volcanoes") for lt , ln, el, name in zip(lat, lon, elev, name): iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100) fgv.add_child(folium.CircleMarker(location=[lt, ln],radius=6, popup=folium.Popup(iframe), fill_color = color_producer(el), color = 'grey',fill_opacity = 0.7)) fgp = folium.FeatureGroup(name="Polulation") 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) map.add_child(folium.LayerControl()) map.save("Map1.html")
def add_dwelling_marker_to_map(m, dwelling, icon_type): x, y = parse_geometry(dwelling['geometry']) lon, lat = rijksdriehoek_to_wsg84(x, y) def percentage(key): return f'{dwelling[key] * 100:.1f}%' def numeric_range(key): mean = dwelling[f'{key}_mean'] range_ = dwelling[f'{key}_95'] if type(range_) == str: lower = range_.replace('[', '').replace(']', '').split(',')[0] upper = range_.replace('[', '').replace(']', '').split(',')[1] return f'{mean} (95%: {lower} to {upper})' else: lower = range_.lower upper = range_.upper return f'{mean:.1f} (95%: {lower:.1f} to {upper:.1f})' results = { 'Base data': { 'vbo ID': f"<samp>{dwelling['vbo_id']}</samp>", 'coordinates': f'({lon:.2f}, {lat:.2f})', 'construction year': dwelling['bouwjaar'], 'surface area': f"{dwelling['oppervlakte']} m<sup>2</sup>", 'dwelling type': f"{dwelling['woningtype'].replace('_', ' ')}", 'neighbourhood': f"{dwelling['buurt_name']} (<samp>{dwelling['buurt_id']}</samp>)" }, 'Energy label': { 'measured': dwelling['energy_label_class'], 'predicted': numeric_range('energy_label_class') }, 'Space heating': { 'district heating': percentage('district_heating_space_p'), 'block heating': percentage('block_heating_space_p'), 'gas boiler': percentage('gas_boiler_space_p'), 'electric boiler': percentage('elec_boiler_space_p'), 'hybrid heat pump': percentage('hybrid_heat_pump_p'), 'electric heat pump': percentage('electric_heat_pump_p') }, 'Water heating': { 'district heating': percentage('district_heating_water_p'), 'block heating': percentage('block_heating_water_p'), 'gas boiler': percentage('gas_boiler_water_p'), 'electric boiler': percentage('elec_boiler_water_p'), 'electric heat pump': percentage('electric_heat_pump_water_p') }, 'Cooking': { 'gas': percentage('gas_cooking_p'), 'electric': percentage('electric_cooking_p') }, 'Insulation': { 'facade R': numeric_range('insulation_facade_r'), 'roof R': numeric_range('insulation_roof_r'), 'floor R': numeric_range('insulation_floor_r'), 'windows R': numeric_range('insulation_window_r') } } table = '<table>' for key, val in results.items(): for index, (key_2, val_2) in enumerate(val.items()): table += f'<tr class="{"new-cat" if index == 0 else ""}">\n' table += f'\t<td>{key if index == 0 else ""}</td>\n' table += f'\t<td>{key_2}</td>\n' table += f'\t<td>{val_2}</td>\n' table += '</tr>\n' table += '</table>' style = ''' <style> * { font-size: 16px; font-family: -apple-system, BlinkMacSystemFont, sans-serif } td { padding-top: 5px; padding-right: 20px; } tr.new-cat > td { padding-top: 15px } td:nth-child(1) { font-weight: bold } td:nth-child(2) { font-weight: bold; text-align: right; } td:nth-child(3) { } </style> ''' html = f''' {style} <div style="width: 45vw; height: 70vh; position: relative"> <div style="border-bottom: 2px solid #ddd; margin-bottom: 10px"> <h3>Dwelling: {dwelling['adres'].replace('_', ' ')}</h3> </div> <div style='overflow-y: auto; height: 90%'> {table} </div> </div> ''' my_popup = folium.Popup(html) if icon_type == 'house': icon = folium.Icon(icon='home', prefix='fa') else: icon = BeautifyIcon( icon_shape='circle-dot', border_color=get_energy_label_colour(dwelling), border_width=4, ) folium.Marker((lon, lat), popup=my_popup, icon=icon).add_to(m)
#This function will map the parsed city to the specified colour based on the colour dictionary. def colorPick(cityName): return colorDic[cityName[0].lower()] #Define the map and place markers on it map = folium.Map(location=[-0.002205, -78.4563984], zoom_start=4, tiles='OpenStreetMap') fgCapCities = folium.FeatureGroup(name="Capital Cities") for lat, lng, name in zip(lat, lng, name): fgCapCities.add_child( folium.CircleMarker(location=[lat, lng], popup=folium.Popup(name, parse_html=True), radius=6, color=colorPick(name), fill_color=colorPick(name), fill=True, fill_opacity=1)) fgCountryPop = folium.FeatureGroup(name="Population") #Adds a layer that colours countries based on their population using GeoJson fgCountryPop.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'
def _map_images( plot_file_format: List[str], result_df: GeoDataFrame, filepaths: List[Union[str, Path]], aoi: GeoDataFrame = None, show_images=True, show_features=False, name_column: str = "id", save_html: Path = None, ) -> folium.Map: """ Displays data.json, and if available, one or multiple results geotiffs. Args: plot_file_format: List of accepted image file formats e.g. [".png"] result_df: GeoDataFrame with scene geometries. aoi: GeoDataFrame of aoi. filepaths: Paths to images to plot. Optional, by default picks up the last downloaded results. show_images: Shows images if True (default). show_features: Show features if True. For quicklooks maps is set to False. name_column: Name of the feature property that provides the Feature/Layer name. save_html: The path for saving folium map as html file. With default None, no file is saved. """ if result_df.shape[0] > 100: result_df = result_df.iloc[:100] logger.info( "Only the first 100 results will be displayed to avoid memory " "issues.") centroid = box(*result_df.total_bounds).centroid m = folium_base_map( lat=centroid.y, lon=centroid.x, ) df_bounds = result_df.bounds list_bounds = df_bounds.values.tolist() raster_filepaths = [ path for path in filepaths if Path(path).suffix in plot_file_format ] try: feature_names = result_df[name_column].to_list() except KeyError: feature_names = [""] * len(result_df.index) if aoi is not None: aoi_style = VECTOR_STYLE.copy() aoi_style["color"] = "red" folium.GeoJson( aoi, name="aoi", style_function=lambda x: aoi_style, highlight_function=lambda x: HIGHLIGHT_STYLE, ).add_to(m) if show_features: for idx, row in result_df.iterrows(): # type: ignore try: feature_name = row.loc[name_column] except KeyError: feature_name = "" layer_name = f"Feature {idx + 1} - {feature_name}" f = folium.GeoJson( row["geometry"], name=layer_name, style_function=lambda x: VECTOR_STYLE, highlight_function=lambda x: HIGHLIGHT_STYLE, ) folium.Popup( f"{layer_name}: {row.drop('geometry', axis=0).to_json()}" ).add_to(f) f.add_to(m) if show_images and raster_filepaths: for idx, (raster_fp, feature_name) in enumerate( zip(raster_filepaths, feature_names)): with rasterio.open(raster_fp) as src: if src.meta["crs"] is None: dst_array = src.read()[:3, :, :] minx, miny, maxx, maxy = list_bounds[idx] else: # Folium requires 4326, streaming blocks are 3857 with WarpedVRT(src, crs="EPSG:4326") as vrt: dst_array = vrt.read()[:3, :, :] minx, miny, maxx, maxy = vrt.bounds m.add_child( folium.raster_layers.ImageOverlay( np.moveaxis(np.stack(dst_array), 0, 2), bounds=[[miny, minx], [maxy, maxx]], # different order. name=f"Image {idx + 1} - {feature_name}", )) # Collapse layer control with too many features. collapsed = bool(result_df.shape[0] > 4) folium.LayerControl(position="bottomleft", collapsed=collapsed).add_to(m) if save_html: save_html = Path(save_html) if not save_html.exists(): save_html.mkdir(parents=True, exist_ok=True) filepath = save_html / "final_map.html" with filepath.open("w") as f: f.write(m._repr_html_()) return m
conn.close() content = '<h2>%s</h2>' % (str(r1['id'])) for loc in json.loads(r1['loc']): content += '<div>%s<div>' % (loc.strip()) content += '<br>' date = '' ut = '' for r2 in res2: date = time.localtime(r2['date']) t = time.strftime('%Y-%m-%d', date) ut = r2['type'] content += '<div>%s <font color="%s">%s</font></div>' % (t, cmap(types.index(ut)), ut) # get multiline string, add to map mls = geojson.loads(r1['geo']) c = folium.PolyLine(locations=mls.coordinates, color=cmap(types.index(ut)), weight=8, opacity=0.7) iframe = branca.element.IFrame(html=content, width=500, height=250) c.add_child(folium.Popup(iframe, max_width=500)) #c.add_child(folium.Popup(str(r1['id']))) #m.add_child(c) c.add_to(feature_groups[types.index(ut)]) for fg in feature_groups: fg.add_to(m) folium.LayerControl().add_to(m) # save map m.save('map.html')
], tiles='Cartodb Positron', zoom_start=4) marker_cluster = MarkerCluster(name='African Locations', overlay=True, control=False, icon_create_function=None) for k in range(kiva_mpi_region_locations_africa.shape[0]): location = kiva_mpi_region_locations_africa.lat.values[ k], kiva_mpi_region_locations_africa.lon.values[k] marker = folium.Marker(location=location, icon=folium.Icon(color='green', icon='ok-sign')) popup = kiva_mpi_region_locations_africa.LocationName.values[k] folium.Popup(popup).add_to(marker) marker_cluster.add_child(marker) marker_cluster.add_to(m) folium.LayerControl().add_to(m) m.save("marker cluster south asia.html") m # ### Clustering locations in Africa # # Click on cluster circle to see clustered points # In[24]:
geolocator = Nominatim(user_agent="tn_explorer") location = geolocator.geocode(address) latitude = location.latitude longitude = location.longitude print('The geograpical coordinate of Chennai are {}, {}.'.format( latitude, longitude)) # In[9]: map_chennai = folium.Map(location=[latitude, longitude], zoom_start=11) # add markers to map for lat, lng, label in zip(df_tn_1['Latitude'], df_tn_1['Longitude'], df_tn_1['Restaurant Name']): 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_chennai) map_chennai # Now lets group our data based on locality # In[10]:
else: return 'red' # Forming group of markers fgv = fl.FeatureGroup(name='Volcanoes') fga = fl.FeatureGroup(name='Active') for i, row in vol_df.iterrows(): iframe = fl.IFrame(html=html % (row['name'], row['name'], row['height']), width=150, height=80) fgv.add_child( fl.CircleMarker(location=[row['lat'], row['lon']], popup=fl.Popup(iframe), color=color_selector(row['height']), radius=6, weight=1, fill=True, fill_opacity=0.8)) for i, row in vol_df_a.iterrows(): iframe = fl.IFrame(html=html % (row['name'], row['name'], row['height']), width=150, height=80) fga.add_child( fl.Marker(location=[row['lat'], row['lon']], popup=fl.Popup(iframe), icon=fl.Icon(color=color_selector(row['height']))))
def map_results(self, show_images=True, name_column: str = "uid") -> None: """ Displays data.json, and if available, one or multiple results geotiffs. Args: show_images: Shows images if True (default), only features if False. name_column: Name of the column that provides the Feature/Layer name. # TODO: Make generic with scene_id column integrated. """ if self.results is None: raise ValueError( "You first need to download the results via job.download_results()!" ) def _style_function(feature): # pylint: disable=unused-argument return { "fillColor": "#5288c4", "color": "blue", "weight": 2.5, "dashArray": "5, 5", } def _highlight_function(feature): # pylint: disable=unused-argument return { "fillColor": "#ffaf00", "color": "red", "weight": 3.5, "dashArray": "5, 5", } # Add feature to map. df: GeoDataFrame = self.get_results_json( as_dataframe=True) # type: ignore centroid = box(*df.total_bounds).centroid m = folium_base_map( lat=centroid.y, lon=centroid.x, ) for idx, row in df.iterrows(): # type: ignore try: feature_name = row.loc[name_column] except KeyError: feature_name = "" layer_name = f"Feature {idx+1} - {feature_name}" f = folium.GeoJson( row["geometry"], name=layer_name, style_function=_style_function, highlight_function=_highlight_function, ) folium.Popup( f"{layer_name}: {row.drop('geometry', axis=0).to_json()}" ).add_to(f) f.add_to(m) # Same: folium.GeoJson(df, name=name_column, style_function=style_function, # highlight_function=highlight_function).add_to(map) # Add image to map. if show_images and self.results is not None: plot_file_format = [".tif"] plottable_images = [ path for path in self.results if Path(path).suffix in plot_file_format ] if plottable_images: dst_crs = "EPSG:4326" filepaths: List[Path] = self.results try: feature_names = df[name_column].to_list() except KeyError: feature_names = ["" for i in range(df.shape[0])] for idx, (raster_fp, feature_name) in enumerate( zip(filepaths, feature_names)): # TODO: Not ideal, streaming images are webmercator, folium requires wgs 84.0 # TODO: Switch to ipyleaflet! # This requires reprojecting on the user pc, not via the api. # Reproject raster and add to map with rasterio.open(raster_fp) as src: dst_profile = src.meta.copy() if src.crs == dst_crs: dst_array = src.read()[:3, :, :] minx, miny, maxx, maxy = src.bounds else: transform, width, height = calculate_default_transform( src.crs, dst_crs, src.width, src.height, *src.bounds) dst_profile.update({ "crs": dst_crs, "transform": transform, "width": width, "height": height, }) with MemoryFile() as memfile: with memfile.open(**dst_profile) as mem: for i in range(1, src.count + 1): reproject( source=rasterio.band(src, i), destination=rasterio.band(mem, i), src_transform=src.transform, src_crs=src.crs, dst_transform=transform, dst_crs=dst_crs, resampling=Resampling.nearest, ) dst_array = mem.read()[:3, :, :] minx, miny, maxx, maxy = mem.bounds # TODO: Make band configuration available m.add_child( folium.raster_layers.ImageOverlay( np.moveaxis(np.stack(dst_array), 0, 2), bounds=[[miny, minx], [maxy, maxx]], # different order. name=f"Image {idx+1} - {feature_name}", )) # Collapse layer control with too many features. if df.shape[0] > 4: # pylint: disable=simplifiable-if-statement #type: ignore collapsed = True else: collapsed = False folium.LayerControl(position="bottomleft", collapsed=collapsed).add_to(m) try: assert get_ipython() is not None display(m) except (AssertionError, NameError): logger.info( "Returning folium map object. To display it directly run in a " "Jupyter notebook!") return m