def mapper(df, is_echo=True): # Initialize the map m = folium.Map(location=[df.mean()["FAC_LAT"], df.mean()["FAC_LONG"]]) # Create the Marker Cluster array #kwargs={"disableClusteringAtZoom": 10, "showCoverageOnHover": False} mc = FastMarkerCluster("") # Add a clickable marker for each facility for index, row in df.iterrows(): mc.add_child( folium.CircleMarker(location=[row["FAC_LAT"], row["FAC_LONG"]], popup=marker_text(row, is_echo), radius=8, color="black", weight=1, fill_color="orange", fill_opacity=.4)) m.add_child(mc) bounds = m.get_bounds() m.fit_bounds(bounds) # Show the map return m
def mapper(df): # Initialize the map m = folium.Map(location=[df.mean()["FAC_LAT"], df.mean()["FAC_LONG"]]) # Create the Marker Cluster array #kwargs={"disableClusteringAtZoom": 10, "showCoverageOnHover": False} mc = FastMarkerCluster("") # Add a clickable marker for each facility for index, row in df.iterrows(): mc.add_child( folium.CircleMarker( location=[row["FAC_LAT"], row["FAC_LONG"]], popup=row["FAC_NAME"] + "<p><a href='" + row["DFR_URL"] + "' target='_blank'>Link to ECHO detailed report</a></p>", radius=8, color="black", weight=1, fill_color="orange", fill_opacity=.4)) m.add_child(mc) bounds = m.get_bounds() m.fit_bounds(bounds) # Show the map return m
def mapper(df, bounds=None, no_text=False): ''' Display a map of the Dataframe passed in. Based on https://medium.com/@bobhaffner/folium-markerclusters-and-fastmarkerclusters-1e03b01cb7b1 Parameters ---------- df : Dataframe The facilities to map. They must have a FAC_LAT and FAC_LONG field. bounds : Dataframe A bounding rectangle--minx, miny, maxx, maxy. Discard points outside. Returns ------- folium.Map ''' # Initialize the map m = folium.Map(location=[df.mean()["FAC_LAT"], df.mean()["FAC_LONG"]]) # Create the Marker Cluster array #kwargs={"disableClusteringAtZoom": 10, "showCoverageOnHover": False} mc = FastMarkerCluster("") # Add a clickable marker for each facility for index, row in df.iterrows(): if (bounds is not None): if (not check_bounds(row, bounds)): continue mc.add_child( folium.CircleMarker(location=[row["FAC_LAT"], row["FAC_LONG"]], popup=marker_text(row, no_text), radius=8, color="black", weight=1, fill_color="orange", fill_opacity=.4)) m.add_child(mc) bounds = m.get_bounds() m.fit_bounds(bounds) # Show the map return m
def mapa(gdf): """Cria o mapa base, insere marcadores e exporta uma arquivo html.""" # Criando mapa base com o folium media_longitude = gdf['LONGITUDE'].mean() media_latitude = gdf['LATITUDE'].mean() ceara = folium.Map(location=[media_longitude,media_latitude],zoom_start=7.5, tiles='stamentoner', width='100%', height='100%') mc = FastMarkerCluster(gdf[['LONGITUDE','LATITUDE',]], popup=list(gdf['Programa'])) ceara.add_child(mc) ceara.save('promac.html')
def make_marker_cluster(gdf, make_centroids=True, points_column='geometry', fast=False, name=None, show=False, basemap=None, **kwargs): """ Makes a marker cluster from a gdf and potentially adds it to a map/feature group. :param GeoDataFrame gdf: A geodataframe. :param bool make_centroids: If true and the geodataframe has polygon geometry, it will make the centroids and use those to make the marker cluster. :param str or int points_column: If make_centroids is False, will assume the pointa are in this column. Defaults to 'geometry'. :param bool fast: If True, use a FastMarkerCluster as opposed to a regular MarkerCluster. :param str name: Defaults to None. If not None, will generate a FeatureGroup with this name and return that instead of the MarkerCluster object. :param bool show: Defaults to False. The show parameter for the FeatureGroup that the marker cluster will be added to. :param folium.Map basemap: Defaults to None. If not none, will add the MarkerCluster or FeatureGroup to the supplied basemap. :param kwargs: kwargs to pass to the FastMarkerCluster or MarkerCluster initialization :return: Either a FeatureGroup or a MarkerCluster. """ # Possibly make centroids if make_centroids: gdf['centroids'] = gdf['geometry'].centroid points_column = 'centroids' # Retrieve points and make markercluster points = [ utilities.simple.retrieve_coords(point) for point in gdf[points_column] ] if fast: marker = FastMarkerCluster(points, **kwargs) else: marker = MarkerCluster(points, **kwargs) # Possibly create featuregroup and possibly add to basemap; then return if name is not None: feature_group = folium.FeatureGroup(name, show=show) marker.add_to(feature_group) if basemap is not None: feature_group.add_to(basemap) return feature_group else: if basemap is not None: marker.add_to(basemap) return marker
def create_map(): X, cluster_labels = generate_random_data(latitude, longitude, 1000, 100) df = pd.DataFrame(X) df.to_csv("geo.csv") # Loads data from csv into pandas dataframe df = pd.read_csv("geo.csv") df.head(2) print() # Stanford coordinates coords = [37.427829, -122.170214] # creates an empty map zoomed in Stanford stan_map = folium.Map(location=coords, zoom_start=12) # creates a marker cluster called “Crime cluster” marker_cluster = FastMarkerCluster( df.iloc[:, 1:].values.tolist()).add_to(stan_map) ''' # add a marker for each event, add it to the cluster, not the map for each in df[:100].iterrows(): # for speed purposes delimited data to 15K folium.Marker(location=[each[1]["0"], each[1]["1"]]).add_to( marker_cluster) ''' display(stan_map) # create HTML interface fg = folium.FeatureGroup(name="Active Shooter") props = lambda x: { "fillColor": "green" if x["properties"]["POP2005"] <= 10000000 else "orange" if 10000000 < x["properties"]["POP2005"] < 20000000 else "red" } stan_map.add_child(fg) ''' stan_map.add_child(folium.GeoJson(data=open( "world_geojson_from_ogr.json", encoding="utf-8-sig").read(), name="Population", style_function=props)) ''' stan_map.add_child(folium.LayerControl()) stan_map.save(outfile="index.html")
def geo_location(read_long_csv, lat_long): # Reading the latitudes and longitudes csv file df = pd.read_csv(read_long_csv) # Using Folium package to plot the lat and long folium_map = folium.Map(location=lat_long, zoom_start=2, tiles='CartoDB dark_matter') FastMarkerCluster( data=list(zip(df['lat'].values, df['lon'].values))).add_to(folium_map) folium.LayerControl().add_to(folium_map) # Saving the map in a html file folium_map.save(outfile='map.html') out = "map.html" # opening the map html file on browser webbrowser.open(out, new=2) # returning the plotted map return folium_map
def document_map(request,pk): mimapa = folium.Map(location=[-34.641552, -58.479811]) document = get_object_or_404(Document, document_id=pk) df = pd.read_csv(document.document) df['longitude'] = df['longitude'].replace(r'\s+', np.nan, regex=True) df['longitude'] = df['longitude'].replace(r'^$', np.nan, regex=True) df['longitude'] = df['longitude'].fillna(-0.99999) df['longitude'] = pd.to_numeric(df['longitude']) df['latitude'] = df['latitude'].replace(r'\s+', np.nan, regex=True) df['latitude'] = df['latitude'].replace(r'^$', np.nan, regex=True) df['latitude'] = df['latitude'].fillna(-0.99999) df['latitude'] = pd.to_numeric(df['latitude']) FastMarkerCluster(data=list(zip(df['latitude'], df['longitude']))).add_to(mimapa) m = mimapa._repr_html_() context = { 'map': m , 'name': document.name, 'description': document.description, 'document': document} return render(request, 'map.html', context)
def render_home(): neighbourhood_groups = [] neighborhoods = [] # accessing cleaned csv file df = main_class_obj.cleaned_df lats2019 = df['latitude'].tolist() lons2019 = df['longitude'].tolist() locations = list(zip(lats2019, lons2019)) # generating folium map with fast marker clusters using latitudes and longitudes map1 = folium.Map(location=[55.585901, -105.750596], zoom_start=3.3) FastMarkerCluster(data=locations).add_to(map1) # saving the html to render it on webpage map1.save(outfile="./static/dashboard-map5.html") return render_template('index.html', neighbourhood_groups=neighbourhood_groups, neighborhoods=neighborhoods)
def mapStops(bbox, stopsList): minLat = bbox[3] minLon = bbox[0] maxLat = bbox[1] maxLon = bbox[2] listpoint = [[maxLat, minLon], [maxLat, maxLon], [minLat, maxLon], [minLat, minLon], [maxLat, minLon]] listpoint = [[float(x[0]), float(x[1])] for x in listpoint] latlon = [(listpoint[0][0] + listpoint[2][0]) / 2, (listpoint[0][1] + listpoint[2][1]) / 2] map_stops = folium.Map(location=latlon, zoom_start=10) line = folium.PolyLine(listpoint) map_stops.add_child(line) markerList = [] for aa in stopsList: markerList.append([aa[1], aa[2]]) points = FastMarkerCluster(markerList, None).add_to(map_stops) return map_stops
def mupLoader(mapElement, data, color): # query latitude and longitude initLen = len(data) print(data) # Cleaned Name cname = 'UserList' # Change Colors here (js callback string) callback = ( 'function (row) {' 'var circle = L.circle(new L.LatLng(row[0], row[1]), {color: "' + color + '", radius: 100});' 'return circle};') # Add Clusters Fm = FastMarkerCluster(data.values, callback=callback, name=cname, overlay=True) mapElement.add_child(Fm)
def get_dept_clusters(dept_df): # Constructing cluster list fast_marker_clusters_tuples = ( (request_df.shape[0], FastMarkerCluster(name=request, data=marker_data_generator(request_df), callback=MARKER_CALLBACK, options={'disableClusteringAtZoom': 17}, show=False)) for request, request_df in dept_df.groupby(["Code"])) # Creating list of clusters, sorted by size fast_marker_clusters = map( lambda marker_tuple: marker_tuple[1], sorted(fast_marker_clusters_tuples, key=lambda marker_tuple: marker_tuple[0], reverse=True)[:TOP_REQUEST_NUMBER]) return fast_marker_clusters
def marker_cluster_fast(named_data, lonlat=True, filename='tmp_marker_cluster.html', verbose=0): if lonlat: if verbose > 0: print('transformed to (lat,lon)') named_data = { name: [(c[1], c[0]) for c in coords] for name, coords in named_data.items() } # get bounding box lons, lats = [], [] for _, coords in named_data.items(): lats.extend([coord[0] for coord in coords]) lons.extend([coord[1] for coord in coords]) w, e, s, n = min(lons), max(lons), min(lats), max(lats) # build map m = folium.Map() add_common_tiles(m) m.fit_bounds([(s, w), (n, e)]) # bind data to map callback = """ function (row) {{ var icon, marker; icon = L.AwesomeMarkers.icon({{ icon: "map-marker", markerColor: "{color}"}}); marker = L.marker(new L.LatLng(row[0], row[1])); marker.setIcon(icon); return marker; }}; """ colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] for i, (name, coords) in enumerate(named_data.items()): if verbose > 0: print('adding layer of', name) FastMarkerCluster( data=coords, callback=callback.format(color=colors[i % len(colors)])).add_to(m) # layer control m.add_child(folium.LayerControl()) m.save(filename)
def test_fast_marker_cluster(): n = 100 np.random.seed(seed=26082009) data = np.array([ np.random.uniform(low=35, high=60, size=n), np.random.uniform(low=-12, high=30, size=n), ]).T m = folium.Map([45., 3.], zoom_start=4) mc = FastMarkerCluster(data).add_to(m) out = normalize(m._parent.render()) # We verify that imports assert '<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.1.0/leaflet.markercluster.js"></script>' in out # noqa assert '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.1.0/MarkerCluster.css"/>' in out # noqa assert '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.1.0/MarkerCluster.Default.css"/>' in out # noqa # Verify the script part is okay. tmpl = Template(""" var {{ this.get_name() }} = (function(){ {{ this.callback }} var data = {{ this.data|tojson }}; var cluster = L.markerClusterGroup({{ this.options|tojson }}); {%- if this.icon_create_function is not none %} cluster.options.iconCreateFunction = {{ this.icon_create_function.strip() }}; {%- endif %} for (var i = 0; i < data.length; i++) { var row = data[i]; var marker = callback(row); marker.addTo(cluster); } cluster.addTo({{ this._parent.get_name() }}); return cluster; })(); """) expected = normalize(tmpl.render(this=mc)) assert expected in out
def makeGraph(): """ latitude = df.Latitude.values longitude = df.Longitude.values """ folium_map = folium.Map( location=[df.Latitude.values.mean(), df.Longitude.values.mean()], tiles='cartodbpositron', zoom_start=4, width="100", height="100") callback = ( 'function (row) {' 'var marker = L.marker(new L.LatLng(row[0], row[1]), {color: "red"});' 'var icon = L.AwesomeMarkers.icon({' "icon: 'info-sign'," "iconColor: 'white'," "markerColor: 'green'," "prefix: 'glyphicon'," "extraClasses: 'fa-rotate-0'" '});' 'marker.setIcon(icon);' "var popup = L.popup({maxWidth: '300'});" "const display_text = {Country: row[2], City: row[3], IP: row[4], bandwidth: row[5], Label: row[6], confidence: row[7], mirai: row[8], organization: row[9], orgType: row[10]};" "var mytext = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> <b>IP:</b> ${display_text.IP} <br><b>Location:</b> ${display_text.City}, ${display_text.Country}<br><b>Bandwidth:</b> ${display_text.bandwidth} b/s<br><b>Label:</b> ${display_text.Label}<br><b>Confidence:</b> ${display_text.confidence} <br><b>Mirai:</b> ${display_text.mirai} <br><b>Organization:</b> ${display_text.organization} <br><b>Organization Type:</b> ${display_text.orgType} </div>`)[0];" "popup.setContent(mytext);" "marker.bindPopup(popup);" 'return marker};') folium_map.add_child( FastMarkerCluster(df[[ 'Latitude', 'Longitude', 'Country', 'City', 'ip', 'scanning Bandwidth', "Label", "Confidence", "Mirai", "Organization", "Organization Type" ]].values.tolist(), callback=callback)) folium_div = folium_map._repr_html_() return folium_div
def test(file,mode=1,date=""): #ficheiro json jFile = file + ".json" #caminho para o ficheiro json filePath = dataPath+jFile #abre o ficheiro readFile = open(filePath) locations = json.load(readFile) #cria o mapa map = folium.Map(zoom_start=6) #numero de localizacoes #print (len(locations['locations'])) #para todos os locais, #retira latitude/longitude #e insere na lista de pontos points = [] for location in locations['locations']: if(date != ""): time = getTime(location) if date in time: appendPoint(points,location) else: appendPoint(points,location) if mode:# =1 , desenha os pontos map.add_child(FastMarkerCluster(points)) map.save(mapsPath+file+"_points"+".html") else: # =0 , desenha o heatmap map.add_child(HeatMap(points,max_val=50)) map.save(mapsPath+file+"_heat"+".html") #fecha o ficheiro readFile.close()
def create_map(csv_file, output_html): mood_content = load_csv_file( csv_file) #Loading the csv file into the mood_content #Classify each mood_content item in country locations mood_location = {} #We are declaring a dictionary that for item in mood_content: if item['location'] not in mood_location: mood_location[item['location']] = {'Positive': 0, 'Negative': 0} mood_location[item['location']][item[ 'mood']] += 1 #for each location the mood is counted according to its occurances my_map = folium.Map() #folium is a library that is used to create a Map my_map.save( output_html) #And then we are saving that map into the html file world = geopandas.read_file( geopandas.datasets.get_path('naturalearth_lowres')) country_names = [] moods = [] for country in mood_location: mood = mood_location[country]['Positive'] / ( mood_location[country]['Positive'] + mood_location[country]['Negative'] ) #We are calculating the overall postive tweets value pecrcentage moods.append(mood) #And we are appending each mood into the moods list country_names.append( country ) # And also we are appending each country name into the country_names list data_to_plot = pd.DataFrame( { 'Country': country_names, 'Mood': moods } ) #We are creating a dataframe inside which we have two columns Country=All country names ,Mood=That says a number of positive tweets of a brand in each country folium.Choropleth( #we are using this folium to color the different parts of a country in a continent geo_data=world, name='choropleth', data=data_to_plot, columns=['Country', 'Mood' ], #Columns that we are going to pass is Country and mood key_on='feature.properties.name', fill_color='YlGn', #Colors are yellow and green fill_opacity=0.7, line_opacity=0.2, legend_name='Mood').add_to(my_map) cluster_data = [] for row in mood_content: #we are retriving each row from the csv table if row['latitude'] != '': #if the latitude and longitude is not empty we are doing the next step cluster_data.append( [float(row['latitude']), float(row['longitude'])] ) # We are passing list of latitude and longitude and appending it into the cluster_data FastMarkerCluster(cluster_data).add_to( my_map ) #we are passing the list of latitudes,logitudes a cluster_data to FastMarkerCluster which forms a cluster kind of thing into the map.So the no of mood items in each longitude and latitude will be in the map folium.LayerControl().add_to( my_map) #we are giving the layer control to the my_map value my_map.save(output_html ) #And at last we are saving the my_map into the output.html
]) ## Distribution of price over regions plt.figure(figsize=(10, 6)) sns.boxplot(y="price", x='neighbourhood_group', data=df) plt.title("Price distribution by region") plt.show() ## Finding the distribution of listings by region plt.figure(figsize=(10, 6)) sns.scatterplot("longitude", "latitude", hue="neighbourhood_group", data=df) plt.title("Distribution of listings by region") plt.show() ## Listing distribution through folium m = folium.Map([1.38255, 103.83580], zoom_start=11) m.add_child(FastMarkerCluster(df[['latitude', 'longitude']].values.tolist())) display(m) ## Review distribution by minimum nights plt.figure(figsize=(10, 6)) sns.scatterplot(x='minimum_nights', y='number_of_reviews', data=df) plt.title("Distribution of reviews by minimum nights") ## Listing barplot distribution by region plt.figure(figsize=(10, 6)) sns.countplot(x='neighbourhood_group', hue="risk_rating", data=df) plt.title("Distribution of risky listings by region") plt.show() ## Listing barplot distribution by room type plt.figure(figsize=(10, 6))
if sLongitude != 0.0 and sLatitude != 0.0: DataClusterList=list([sLatitude, sLongitude]) DataPointList=list([sLatitude, sLongitude, sDescription]) t+=1 if t==1: DataCluster=[DataClusterList] DataPoint=[DataPointList] else: DataCluster.append(DataClusterList) DataPoint.append(DataPointList) data=DataCluster pins=pd.DataFrame(DataPoint) pins.columns = [ 'Latitude','Longitude','Description'] ################################################################ stops_map1 = Map(location=[48.1459806, 11.4985484], zoom_start=5) marker_cluster = FastMarkerCluster(data).add_to(stops_map1) sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard1.html' stops_map1.save(sFileNameHtml) webbrowser.open('file://' + os.path.realpath(sFileNameHtml)) ################################################################ stops_map2 = Map(location=[48.1459806, 11.4985484], zoom_start=5) for name, row in pins.iloc[:100].iterrows(): Marker([row["Latitude"],row["Longitude"]], popup=row["Description"]).add_to(stops_map2) sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard2.html' stops_map2.save(sFileNameHtml) webbrowser.open('file://' + os.path.realpath(sFileNameHtml)) ################################################################ stops_heatmap = Map(location=[48.1459806, 11.4985484], zoom_start=5) stops_heatmap.add_child(HeatMap([[row["Latitude"], row["Longitude"]] for name, row in pins.iloc[:100].iterrows()])) sFileNameHtml=Base+'/02-Krennwallner/06-Report/01-EDS/02-Python/Billboard_heatmap.html' stops_heatmap.save(sFileNameHtml)
"icon: 'info-sign'," "iconColor: 'white'," "markerColor: 'red'," "prefix: 'glyphicon'," "extraClasses: 'fa-rotate-0'" '});' 'marker.setIcon(icon);' "var popup = L.popup({maxWidth: '300'});" "const display_text = {text: row[2]};" "var mytext = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[0];" "popup.setContent(mytext);" "marker.bindPopup(popup);" 'return marker};') FastMarkerCluster(data=list( zip(data['lat_y1'].values, data['lon_x1'].values, data['BeachName'].values)), callback=callback).add_to(folium_map) folium.LayerControl().add_to(folium_map) folium_map.save(f'{here}/templates/{MAP_FILE}') # Clean files logging.info("Cleaning files...") for path_spec in CLEAN_FILES: # Make paths absolute and relative to this path abs_paths = glob(os.path.normpath(os.path.join(here, path_spec))) for path in [str(p) for p in abs_paths]: if not path.startswith(here): # Die if path in CLEAN_FILES is absolute + outside this directory raise ValueError("%s is not a path inside %s" % (path, here))
from folium.plugins import FastMarkerCluster import pandas as pd import folium df = pd.read_csv("addresses_geocoded.csv", index_col=0) #print(df.head(5)) df = df.dropna() df = df.reset_index(drop=True) #print(df) folium_map = folium.Map(location=[37.983810, 23.727539], zoom_start=2, tiles='CartoDB dark_matter') #folium_map.save('map.html') FastMarkerCluster(data=list(zip(df['Latitude'].values, df['Longitude'].values))).add_to(folium_map) folium.LayerControl().add_to(folium_map) folium_map folium_map.save('map.html')
#import streamlit as st import pandas as pd import folium from folium.plugins import FastMarkerCluster deathlocs = pd.read_csv("datas.csv") folium_map = folium.Map(tiles='CartoDB dark_matter') FastMarkerCluster(data=list(zip(deathlocs['lat'].values, deathlocs['lon'].values))).add_to(folium_map) folium.LayerControl().add_to(folium_map) folium_map.save('index.html') #st.map(deathlocs)
listings = listings.drop(columns=['neighbourhood_group']) listings['host_response_rate'] = pd.to_numeric( listings['host_response_rate'].str.strip('%')) listings.head() feq = listings['neighbourhood'].value_counts().sort_values(ascending=True) feq.plot.barh(figsize=(10, 8), color='b', width=1) plt.title("Number of listings by neighbourhood", fontsize=20) plt.xlabel('Number of listings', fontsize=12) plt.show() lats2018 = listings['latitude'].tolist() lons2018 = listings['longitude'].tolist() locations = list(zip(lats2018, lons2018)) map1 = folium.Map(location=[52.3680, 4.9036], zoom_start=11.5) FastMarkerCluster(data=locations).add_to(map1) map1 freq = listings['room_type'].value_counts().sort_values(ascending=True) freq.plot.barh(figsize=(15, 3), width=1, color=["g", "b", "r"]) plt.show() listings.property_type.unique() prop = listings.groupby(['property_type', 'room_type']).room_type.count() prop = prop.unstack() prop['total'] = prop.iloc[:, 0:3].sum(axis=1) prop = prop.sort_values(by=['total']) prop = prop[prop['total'] >= 100] prop = prop.drop(columns=['total']) prop.plot(kind='barh', stacked=True, color=["r", "b", "g"],
icon = L.AwesomeMarkers.icon({ icon: "map-marker", markerColor: "red"}); marker = L.marker(new L.LatLng(row[0], row[1])); marker.setIcon(icon); marker.bindPopup('dwd weather station').openPopup marker.on('click', onClick); function onClick(e) { var popup = e.target.getPopup(); popup.setContent("This is a weather station at " + e.latlng.toString()) } return marker; };""" #getting data from stations dictionary stationnames = [] lats = [] lons = [] for k, v in Stations.items(): stationnames.append(v.name) lats.append(float(v.geobr)) lons.append(float(v.geola)) FastMarkerCluster( data=list(zip(lats, lons)), callback=callback #[personalized_callback(name) for name in stationnames] ).add_to(map_1) #save map and open in browser map_1.save('./map.html') webbrowser.open('./map.html')
def plot_and_save_map(df, filename): # seed = int(np.random.uniform() * 100) # df = df.sample(frac=0.5, replace=False, random_state=seed) # print("LENGTH OF SAMPLED DF " + str(len(df))) lat_long_df = df print() print(lat_long_df) print(len(lat_long_df)) # create map map = folium.Map( location=[53.8, 4.5], tiles='cartodbpositron', zoom_start=3, ) # create layers callback = ( 'function (row) {' 'var marker = L.marker(new L.LatLng(row[0], row[1]), {color: "#8a8a8a"});' 'var icon = L.AwesomeMarkers.icon({' "icon: 'user'," "iconColor: 'white'," "markerColor: 'black'," "prefix: 'glyphicon'," "extraClasses: 'fa-rotate-0'" '});' 'marker.setIcon(icon);' 'return marker};') #"var popup = L.popup({maxWidth: '300'});" #"const display_text = {text: row[2]};" #"var mytext = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[0];" #"popup.setContent(mytext);" #"marker.bindPopup(popup);" #'return marker};') # Density layer FastMarkerCluster(data=list( zip(lat_long_df['geo_lat'].values, lat_long_df['geo_long'].values)), name='Density', callback=callback).add_to(map) # Sentiment layer sentiment_layer = folium.FeatureGroup(name="Sentiment") for index, row in lat_long_df.iterrows(): sentiment_layer.add_child( folium.CircleMarker( [row['geo_lat'], row['geo_long']], radius=6, color=row['hex_colour'], fill=True, fill_opacity=0.6, popup=('Sentiment: ' + str(row['sentiment'])[0:5] + '\n Classification: ' + str(row['labels'])))).add_to(map) map.add_child(sentiment_layer, name='Sentiment') # Classification layer classification_layer = folium.FeatureGroup(name="Classification") for index, row in lat_long_df.iterrows(): classification_layer.add_child( folium.CircleMarker( [row['geo_lat'], row['geo_long']], radius=6, color=row['classification_colour'], fill=True, fill_opacity=0.3, popup=('Sentiment: ' + str(row['sentiment'])[0:5] + '\n Classification: ' + str(row['labels'])))).add_to(map) map.add_child(classification_layer, name='Classification') # heatmap layer # convert to (n, 2) nd-array format for heatmap lat_long_matrix = lat_long_df[['geo_lat', 'geo_long']].as_matrix() map.add_child(HeatMap(lat_long_matrix, radius=12, name='Heatmap')) folium.LayerControl().add_to(map) map.save(filename)
time = row['date_start'] iframe = folium.IFrame(table('Deaths', name, deaths, time), width=width, height=height) popups[year].append(iframe) h = folium.FeatureGroup(name='Deaths') print(len(locations)) print(len(popups)) #for year in tqdm(conflict_df.date_start.unique()-1989): # # mc = MarkerCluster(locations=locations[year], popups=popups[year], overlay=True, control=True) # mc.add_to(m) #folium.LayerControl().add_to(m) h.add_child(FastMarkerCluster(locations)) #m.add_child(h) m.save(os.path.join('results', "output_map.html")) m = folium.Map(tiles='cartodbpositron', world_copy_jump=True, no_wrap=True) event_list = conflict_df[["latitude", "longitude", "best", "date_start"]] list_of_event = [[row.latitude, row.longitude, row.best] for row in event_list.itertuples()] date_list = [row.date_start for row in event_list.itertuples()] hm = HeatMapWithTime(data=list_of_event[:100], index=event_list.date_start[:100], max_opacity=0.3) hm.add_to(m) m.save(os.path.join('results', "output_map_heat.html"))
def plot_and_save_map(df, filename, data_path): """ Extract coordinates, plot on an interactive map and save to html file """ # N = 3000 # lat_long_df = df.head(N) lat_long_df = df #seed = int(np.random.uniform() * 100) #df = df.sample(frac=0.6, replace=False, random_state=seed) #print("LENGTH OF SAMPLED DF " + str(len(df))) #lat_long_df = df #lat_long_df[['geo_lat', 'geo_long']] = lat_long_df['location'].apply(lambda x: get_latitude_longitude(x)) #lat_long_df['location'] = lat_long_df['location'].apply(lambda x: convert_to_string(x)) #lat_long_df['geo_lat'] = lat_long_df['geo_lat'].apply(lambda x: convert_to_string(x)) # # drop NaNs and save latitude longitude data to csv #lat_long_df.dropna(subset=['geo_lat']) #lat_long_df = lat_long_df.loc[lat_long_df['geo_lat'] != 'NaN'] #lat_long_df = lat_long_df.loc[lat_long_df['geo_lat'] != 'nan'] #lat_long_df.to_csv(data_path, index=False) print() print("LAT LONG DF:") print(lat_long_df) print(len(lat_long_df)) # create map map = folium.Map( location=[53.8, 4.5], tiles='cartodbpositron', zoom_start=3, ) # create layers callback = ('function (row) {' 'var marker = L.marker(new L.LatLng(row[0], row[1]), {color: "#8a8a8a"});' 'var icon = L.AwesomeMarkers.icon({' "icon: 'user'," "iconColor: 'white'," "markerColor: 'black'," "prefix: 'glyphicon'," "extraClasses: 'fa-rotate-0'" '});' 'marker.setIcon(icon);' 'return marker};') iconCreateFunction = ('function(cluster) {' 'var childCount = cluster.getChildCount();' 'var c = " marker-cluster-medium";' # 'if (childCount < 50) {' # 'c += "large";' # '} else if (childCount < 300) {' # 'c += "medium";' # '} else {' # 'c += "small";' # '}' 'return new L.DivIcon({ html: "<div><span>" + childCount + "</span></div>", className: "marker-cluster" + c, iconSize: new L.Point(35, 35) });}') # Density layer FastMarkerCluster( data=list(zip(lat_long_df['geo_lat'].values, lat_long_df['geo_long'].values)), name='Density', icon_create_function=iconCreateFunction, callback=callback ).add_to(map) # Sentiment layer sentiment_layer = folium.FeatureGroup(name="Sentiment") for index, row in lat_long_df.iterrows(): sentiment_layer.add_child(folium.CircleMarker( [row['geo_lat'], row['geo_long']], radius=3, color='clear', fill_color=row['hex_colour'], fill='true', fill_opacity=0.75, popup=('Sentiment: ' + str(row['sentiment'])[0:5] + '\n Classification: ' + str(row['labels']) ) )).add_to(map) map.add_child(sentiment_layer, name='Sentiment') # Classification layer classification_layer = folium.FeatureGroup(name="Classification") for index, row in lat_long_df.iterrows(): classification_layer.add_child(folium.CircleMarker( [row['geo_lat'], row['geo_long']], radius=3, color='clear', fill_color=row['classification_colour'], fill='true', fill_opacity=0.75, popup=('Sentiment: ' + str(row['sentiment'])[0:5] + '\n Classification: ' + str(row['labels']) ) )).add_to(map) map.add_child(classification_layer, name='Classification') # heatmap layer lat_long_matrix = lat_long_df[['geo_lat', 'geo_long']].as_matrix() map.add_child( HeatMap(lat_long_matrix, radius=12, name='Heatmap') ) folium.LayerControl().add_to(map) map.save(filename)
def well_map(): url = 'https://npdfactpages.npd.no/downloads/shape/wlbPoint.zip' # change path to your local directory urllib.request.urlretrieve(url, 'data/wlbPoint.zip') # change path to your local directory wells_explo = geopandas.read_file('zip://data/wlbPoint.zip', encoding='utf-8') wells_explo['wlbEwDesDeg'] = wells_explo['geometry'].x wells_explo['wlbNsDecDeg'] = wells_explo['geometry'].y wells_explo_sel = wells_explo.filter([ 'wbName', 'well_name', 'discovery', 'field', 'prodLicenc', 'well_type', 'drilOperat', 'entryYear', 'cmplYear', 'content', 'main_area', 'totalDepth', 'age_at_TD', 'fmTD', 'discWelbor', 'geometry', 'wlbEwDesDeg', 'wlbNsDecDeg' ], axis=1) wells_explo_all = wells_explo_sel.loc[wells_explo_sel['well_type'].isin( ['EXPLORATION'])] map_wells = folium.Map(location=[ wells_explo_all['wlbNsDecDeg'].mean(), wells_explo_all['wlbEwDesDeg'].mean() ], zoom_start=5, tiles='cartodbpositron') fs = Fullscreen() # adding an extra map background in the layer menu tile = folium.TileLayer('OpenStreetMap').add_to(map_wells) """ defining parameters for our markers and the popups when clicking on single markers """ callback = ( 'function (row) {' 'var marker = L.marker(new L.LatLng(row[0], row[1]));' 'var icon = L.AwesomeMarkers.icon({' "icon: 'star'," "iconColor: 'black'," "markerColor: 'lightgray'," '});' 'marker.setIcon(icon);' "var popup = L.popup({maxWidth: '300'});" "const display_text = {text: '<b>Name: </b>' + row[2] + '</br>' + '<b> Age at TD: </b>' + row[3]};" "var mytext = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[0];" "popup.setContent(mytext);" "marker.bindPopup(popup);" 'return marker};') """ creating clusters with FastMarkerCluster """ fmc = FastMarkerCluster( wells_explo_all[['wlbNsDecDeg', 'wlbEwDesDeg', 'wbName', 'age_at_TD']].values.tolist(), callback=callback) fmc.layer_name = 'Exploration Wells' map_wells.add_child(fmc) # adding fastmarkerclusters to map map_wells.add_child(fs) # adding fullscreen button to map folium.LayerControl().add_to(map_wells) # adding layers to map return map_wells._repr_html_()
} df_new['lat_long'] = df_new['list_unique_city'].map(d) df_new = df_new.drop(columns='list_unique_city') df_new['lat_long'] = df_new['lat_long'].astype(str) lat_long = df_new['lat_long'].str.strip('()').str.split( ', ', expand=True).rename(columns={ 0: 'Latitude', 1: 'Longitude' }) final_df = pd.merge(df_new, lat_long, left_index=True, right_index=True) final_df = final_df.drop(columns='lat_long') final_df[['Latitude', 'Longitude']] = final_df[['Latitude', 'Longitude']].astype(float) # center on Liberty Bell m = folium.Map(location=[31.7683, 35.2137], zoom_start=4) # add marker for Liberty Bell m.add_child( FastMarkerCluster(final_df[['Latitude', 'Longitude']].values.tolist())) # call to render Folium map in Streamlit folium_static(m)
def create_map(self, data): try: len( data ) #it is initialized as 0 so it will error if its 0 and will go to except if len(data) >= 5000: # ============================== FAST CLUSTER ============================== print("Creating map...") m2 = folium.Map( location=[40, -100], tiles='cartodbdark_matter', # cartodbdark_matter #cartodbpositron #stamenwatercolor #stamenterrain #openstreetmap zoom_start=3.5, min_zoom=3.5, ) # callback = (''' function (row) { var circle = L.circle(new L.LatLng(row[0], row[1]), {color: '#1f77b4', radius: 100}); return circle}; ''') m2.add_child( FastMarkerCluster(data[['Start_Lat', 'Start_Lng']].values.tolist(), callback=callback)) m2.save("map.html") #m2.save("mapcluster.html") else: # ============================== CREATE CIRCLE INDIVIDUAL POINT MAP ============================== # MAP - Create a Map instance print("Creating map...") # create gradient color for map mlength = len(data) n = 4 color = plt.cm.brg(np.linspace(0.01, 0.5, n)) #CMRmap, gnuplot2 colors = [] for i in range(int(mlength / n)): for j in color: colors.append(matplotlib.colors.to_hex(j)) print(color) print(list(colors)) m = folium.Map( location=[40, -100], tiles='cartodbdark_matter', # cartodbdark_matter #cartodbpositron #stamenwatercolor #stamenterrain #openstreetmap zoom_start=3.5, min_zoom=3.5, ) for color, sev, lat, lan, description, street, city, state, zipcode in zip( colors, data['Severity'], data['Start_Lat'], data['Start_Lng'], data['Description'], data['Street'], data['City'], data['State'], data['Zipcode']): print(description, type(description), street, type(street), city, type(city), state, type(state), zipcode, type(zipcode)) popup = "<b>Severity: " + str( sev ) + "</b> <br><br> Address: " + street + ", " + city + ", " + state + ", " + zipcode + "<br><br><i>Description: " + description + "</i>" if sev == 1: color = "green" elif sev == 2: color = "#1f77b4" elif sev == 3: color = "#5800a7" elif sev == 4: color = "#fe0100" else: color = "white" # ============================== CIRCLE ============================== # CIRCLE MARKERS - Add the dataframe markers in the map folium.Circle( #location=[data.iloc[i]['Start_Lat'], data.iloc[i]['Start_Lng']], #popup=data.iloc[i]['Street'] + ", " + data.iloc[i]['City'] + ", " + data.iloc[i]['State'] + ", " + data.iloc[i]['Zipcode'], location=[lat, lan], popup=popup, radius=1000, #stroke settings stroke=False, weight=1, color=color, opacity=0.2, #fill settings fill=True, fill_color=color, fill_opacity=0.8, ).add_to(m) # Save the map m.save("map.html") except: print("Initializing map...") m3 = folium.Map( location=[40, -100], #37.0902, -95.7129 tiles='cartodbdark_matter', # cartodbdark_matter #cartodbpositron #stamenwatercolor #stamenterrain #openstreetmap zoom_start=3.5, min_zoom=3.5, ) m3.save("map.html") print("Map created")