def generate_map(marker_layer=True, marker_num=None, crime_heatmap=True, choropleth_zipcode=True): """ Funtion to generate map demo Input: marker_layer --- bool, whether to generate marker for each house marker_num --- number of markers to generate in the map, if None, all the markers will generate crime_heatmap --- bool, whether to generate a map of crime incidence choropleth_zipcode --- bool, choropleth layer of average house price in each zipcode return a html file """ data = pd.read_csv("../Data/house_crime_data.csv", parse_dates=['date']) data['zipcode'] = data['zipcode'].astype(str) crime_data = pd.read_csv('../Data/cleaned_crime_data.csv', parse_dates=['incident_datetime']) zipcode_data = data.groupby('zipcode').mean() zipcode_data['count'] = data.groupby('zipcode').count()['id'] zipcode_data.reset_index(inplace=True) # Generate base map layer geo_path = '../Data/zipcode_king_county.geojson' Map = folium.Map(location=[data['lat'].mean(), data['long'].mean()], zoom_start=11, API_key='zipcode') # Generate marker map layer if marker_layer == True: if marker_num is not None: MAX_SHOW = marker_num marker_cluster = folium.MarkerCluster(name='House Cluster').add_to(Map) for iters, row in data[0:MAX_SHOW].iterrows(): folium.Marker([row["lat"], row["long"]], popup=hc.popup_text(iters, row)).add_to(marker_cluster) else: marker_cluster = folium.MarkerCluster(name='House Cluster').add_to(Map) for iters, row in data.iterrows(): folium.Marker([row["lat"], row["long"]], popup=hc.popup_text(iters, row)).add_to(marker_cluster) # Generate zipcode vs. house price layer if choropleth_zipcode == True: Map.choropleth(geo_path=geo_path, data=zipcode_data, columns=['zipcode', 'price'], key_on='feature.properties.ZCTA5CE10', fill_color='OrRd', threshold_scale=[200000, 400000, 600000, 800000, 1000000, 1500000], fill_opacity=0.6, line_opacity=0.2, legend_name='House Price') # Generate Crime heatmap if crime_heatmap == True: Map.add_children(plugins.HeatMap([[row["latitude"], row["longitude"]] for iters, row in crime_data.iterrows()], name='Crime Incidence', min_opacity=0.5, max_zoom=18, radius=11)) folium.LayerControl().add_to(Map) Map.save('Map.html')
def shortestPathNavigation(userLoc, destinLoc): """ :type userLoc: List[float] of size 2 :type destinLoc: List[float] of size 2 """ G = ox.graph_from_point(userLoc, distance = 2000, distance_type = 'network', network_type = 'walk') Gnodes = G.nodes() # Get the nearest node in the system of the given location origin_node = ox.get_nearest_node(G, userLoc) destin_node = ox.get_nearest_node(G, destinLoc) # Get the lat&lng of the approximated location origin_point, destin_point = [[Gnodes[i]['y'],Gnodes[i]['x']] for i in [origin_node, destin_node]] # Get the shortest route's nodes' indices route = nx.shortest_path(G, origin_node,destin_node, weight = 'length') fig,ax = ox.plot_graph_route(G,route,origin_point = origin_point, destination_point = destin_point) # Get the shortest route's lat&lng the_route = [[G.nodes()[i]['y'],G.nodes()[i]['x']] for i in route] # Create map and add markers of origin&destin to the map m = folium.Map(location = userLoc, zoom_start = 13) marker_cluster = folium.MarkerCluster().add_to(m) folium.Marker(origin_point, popup = 'Origin').add_to(marker_cluster) folium.Marker(destin_point, popup = 'Dest').add_to(marker_cluster) # Add the shortest path to the map shortest_path = folium.PolyLine(the_route).add_to(m) # More parameters: #weight=15,#color='#8EE9FF' # Show the map return m
def create(self): gcode = self.geocode(self.city) try: mCluster = folium.Map(location=[gcode.latitude, gcode.longitude], zoom_start=13) marker_cluster = folium.MarkerCluster().add_to(mCluster) def worker(location, city, days): gcode = self.geocode(location + " " + city) colors = [ "green", "red", "blue", "brown", "yellow", "orange", "purple" ] try: folium.Marker([gcode.latitude, gcode.longitude], popup=location.title() + ". " + str(len(days)) + " day(s) in total visiting.", icon=folium.Icon( color=colors[days[0] % len(colors)], icon='info-sign')).add_to(marker_cluster) except: print('error retrieving location - {}'.format(location + " " + city)) pass return for location in self.locations.keys(): worker(location, self.city, self.locations[location]['days']) mCluster.save(self.file) except: print('error retrieving city - {}'.format(city)) return
def marker_cluster_map(df_, country, cluster=0): ''' Create a marker cluster map of simulations in a particular country. :param df: dataframe from which data is pulled :param country: country for which to map simulations :param cluster: the cluster to map; default = 0, which means all clusters are mapped ''' centers = pd.read_pickle('data/centers.pkl') df = df_[df_['Country'] == country] if cluster != 0: df = df_[df_['Cluster'] == cluster] center_lat = centers.loc[centers['ISO3136'] == country, 'LAT'].tolist()[0] center_lng = centers.loc[centers['ISO3136'] == country, 'LONG'].tolist()[0] m = folium.Map(location=[center_lat, center_lng], zoom_start=6, max_zoom=10, control_scale=True) # create a marker cluster marker_cluster = folium.MarkerCluster('Simulations Cluster').add_to(m) latitude = df.Latitude.values longitude = df.Longitude.values lat_lng = list(zip(latitude, longitude)) for idx, (lat, lng) in enumerate(lat_lng): folium.Marker(location=[lat, lng]).add_to(marker_cluster) m.save('img/maps/marker_cluster.html')
def make_map(geojson_file, map_file): tweet_map = folium.Map(location=[50, 5], zoom_start=5) marker_cluster = folium.MarkerCluster().add_to(tweet_map) geojson_layer = folium.GeoJson(open(geojson_file), name='geojson') geojson_layer.add_to(marker_cluster) tweet_map.save(map_file)
def house_cluster(HouseData, HouseUrl): house_map = folium.Map( location=[HouseData['lat'].mean(), HouseData['long'].mean()], zoom_start=10) marker_cluster = folium.MarkerCluster().add_to(house_map) for iters, row in data.iterrows(): folium.Marker([row["lat"], row["long"]], popup=popup_text(iters, row)).add_to(marker_cluster) # Save the house cluster map to a html and open it in broswer. house_map.save(HouseUrl)
def make_map(geojson_file, map_file): tweet_map = folium.Map(location=[50, 5], zoom_start=5) marker_cluster = folium.MarkerCluster().add_to(tweet_map) geodata = json.load(open(geojson_file)) for tweet in geodata['features']: tweet['geometry']['coordinates'].reverse() marker = folium.Marker(tweet['geometry']['coordinates'], popup=tweet['properties']['text']) marker.add_to(marker_cluster) tweet_map.save(map_file)
def make_map(geojson_file, map_file): # Create folium map centered at (latitude, longitude) tweet_map = folium.Map(location=[50, -50], zoom_start=2) # In case Tweets get too clustered marker_cluster = folium.MarkerCluster().add_to(tweet_map) geodata = json.load(open(geojson_file)) for tweet in geodata['features']: tweet['geometry']['coordinates'].reverse() marker = folium.Marker(tweet['geometry']['coordinates'], popup=tweet['properties']['text']) marker.add_to(marker_cluster) tweet_map.save(map_file)
def createAsync(self): gcode = self.geocode(self.city) try: mCluster = folium.Map(location=[gcode.latitude, gcode.longitude], zoom_start=13) marker_cluster = folium.MarkerCluster().add_to(mCluster) def worker(location, city): gcode = self.geocode(location + " " + city) try: folium.Marker([gcode.latitude, gcode.longitude], popup=location, icon=folium.Icon( color="green", icon='no-sign')).add_to(marker_cluster) except: print('error retrieving location - {}'.format(location + " " + city)) pass return def createMap(threads, file_name): for thread in threads: thread.join() # all threads finished mCluster.save(file_name) threads = [] for location in self.locations.keys: t = threading.Thread(name=location, target=worker, args=( location, self.city, )) threads.append(t) t.start() t = threading.Thread(name='createMap', target=createMap, args=( threads, self.file, )) t.start() except: print('error retrieving city - {}'.format(city)) return
def folium_cityweather(datafile, outfile): df = pd.read_csv(datafile, encoding='latin1') df.columns = map(str.lower, df.columns) locNow = weather.get_loc_by_ip() df['icon'] = df['icon'].replace(['01d', '02d'], 'asterisk') df['icon'] = df['icon'].replace(['03d', '04d'], 'cloud') df['icon'] = df['icon'].replace(['09d', '10d'], 'tint') df['icon'] = df['icon'].replace(['11d', '13d', '50d'], 'map-marker') df['color'] = 'blue' df.loc[df.icon == 'asterisk', 'color'] = 'yellow' df.loc[df.icon == 'cloud', 'color'] = 'lightgray' df.loc[df.icon == 'map-marker', 'color'] = 'green' map_osm = folium.Map(location=[locNow[0], locNow[1]], tiles='cartodbpositron', control_scale=True, zoom_start=4) folium.TileLayer( tiles= 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', attr= 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS,AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community', name='satellite').add_to(map_osm) for i in ['wind_new', 'precipitation_new', 'temp_new']: url = 'http://tile.openweathermap.org/map/' + i + '/{z}/{x}/{y}.png?appid=' + keys.key2 folium.TileLayer(tiles=url, attr='tile.openweathermap.org', name=i[:-4], overlay=True).add_to(map_osm) mc = folium.MarkerCluster(name='local weather').add_to(map_osm) for row in range(0, len(df)): folium.Marker( [df['lat'][row], df['lon'][row]], # radius = df['temp'][row], icon=folium.Icon(color=df['color'][row], icon=df['icon'][row]), popup='Location: ' + df['name'][row] + ', ' + 'Temperature: ' + str(df['temp'][row])).add_to(mc) folium.LayerControl().add_to(map_osm) mc.save(outfile)
def showMarkers(data): """ :type data: dataFrame """ lats = list(data['latitude']) lngs = list(data['longitude']) centralY, centralX = 0, 0 for i in range(len(lats)): centralY += lats[i] centralX += lngs[i] centralLoc = [centralY, centralX] m = folium.Map(location = centralLoc) # folium.Map(location=[longitude[0], latitude[0]]) marker_cluster = folium.MarkerCluster().add_to(m) for name, row in data[:1000].iterrows(): folium.Marker([row["latitude"], row["longitude"]], popup=row["name"]).add_to(marker_cluster) m.save('stops.html') return m
def get_map(self, create_html=True): """Strike data should be a pd.DF from the WWLN data files read by read_WWLN()""" strike_data = self.df num_rows = len(self.df) if num_rows > 1000: print("Warning, you have requested lots of data be mapped." / " Limiting your request to the first 1,000 rows" / " as this is currently only a preview feature.") strike_data = self.df[0:1000] m = folium.Map(location=[0.0, 0.01], zoom_start=2) marker_cluster = folium.MarkerCluster().add_to(m) for event in strike_data.index: self.add_to_map(map_obj=m, date_time=strike_data.dt[event], cluster_obj=marker_cluster, lat=strike_data.geometry[event].y, lon=strike_data.geometry[event].x, key=event) if create_html: data_date = strike_data.dt[0].split()[0] m.save('map_{0}.html'.format(data_date)) return m
def marker_cluster_map(df, country, c_num): '''Create a marker cluster map of simulations for a cluster in the specified country''' df = df[df['Country'] == country] if c_num != 0: df = df[df['Cluster'] == c_num] centers = pd.read_pickle('../data/centers.pkl') center_lat = centers.loc[centers['ISO3136'] == country, 'LAT'].tolist()[0] center_lng = centers.loc[centers['ISO3136'] == country, 'LONG'].tolist()[0] m = folium.Map(location=[center_lat, center_lng], zoom_start=5.5, max_zoom=10, control_scale=True) # create a marker cluster marker_cluster = folium.MarkerCluster('Simulations Cluster').add_to(m) latitude = df.Latitude.values longitude = df.Longitude.values lat_lng = list(zip(latitude, longitude)) for idx, (lat, lng) in enumerate(lat_lng): folium.Marker(location=[lat, lng]).add_to(marker_cluster) m.save('templates/marker_cluster_{}_{}.html'.format(country, c_num))
HOUSE_URL = 'houses.html' HOUSE_HEAT_URL = "househeatmap.html" CRIME_HEAT_URL = "crimeheatmap.html" pd.set_option('display.max_columns', None) # To display all columns # Read in king county house data. data = pd.read_csv("../../Data/kc_house_data.csv", parse_dates=['date']) data['zipcode'] = data['zipcode'].astype(str) ## Create one map showing each listing of in house dataset and show in browser. # Use folium Map function to plot underlying basic map. house_map = folium.Map(location=[data['lat'].mean(), data['long'].mean()], zoom_start=10) # Define clusters to show house clusters to add to the underlying houses_map. marker_cluster = folium.MarkerCluster().add_to(house_map) # Iteratively add interactive clusters to the basic map. # When mouse-over the cluster, show house listing information: # sqft, price. for iters, row in data[0:MAX_SHOW].iterrows(): folium.Marker([row["lat"], row["long"]], popup="{0} sqft: Sold for $ {1}"\ .format(row["sqft_living"], row["price"])).add_to(marker_cluster) # Save the house cluster map to a html and open it in broswer. house_map.save(HOUSE_URL) webbrowser.open('file://' + os.path.realpath(HOUSE_URL), new=2) ## Create one map showing the frequency of house sales and show in browser. # Use folium Map function to plot underlying basic map
import pandas import folium sismos = pandas.read_csv('sismo10dias.csv') mexico = folium.Map(location=[23.000, -102.000], zoom_start = 4) mapCluster = folium.MarkerCluster("Sismos").add_to(mexico) for r in sismos[0:213].iterrows(): m = r[1]['Magnitud'] f = r[1]['Fecha'] if (m >= 4.5):col = 'red' if (m > 3.5 and m < 4.5):col = 'orange' if (m < 3.5):col = 'green' info = "Mag:" + str(m) + " Fecha:" + f folium.Marker((r[1]['Latitud'],r[1]['Longitud']), popup = info,icon =folium.Icon( col,icon='info-sign')).add_to(mapCluster) mexico.save('map.html
# Python Data Science and Analytics. # Data Science is a field in computer science that is dedicated to analyzing patterns in raw data using # techniques like Artificial Intelligence (AI), Machine Learning (ML), mathematical functions, and # statistical algorithms. # In this script, we'll look at how to leverage tools like Pandas to explore and map out police activity # in Montgomery County, Maryland. # Using the excellent folium package, we can now visualize where all the stops occurred. # Folium allows you to easily create interactive maps in Python by leveraging leaflet. In order to preserve # performance, we'll only visualize the first 1000 rows of morning_rush: import folium from folium import plugins stops_map = folium.Map(location=[39.0836, -77.1483], zoom_start=11) marker_cluster = folium.MarkerCluster().add_to(stops_map) for name, row in morning_rush.iloc[:1000].iterrows(): folium.Marker([row["longitude"], row["latitude"]], popup=row["description"]).add_to(marker_cluster) stops_map.create_map('stops.html') stops_map
with open(counties_fn) as f: dat = json.load(f) for feat in (dat['features']): name = feat['properties']['NAME'] gj = flm.GeoJson(data=feat, overlay=True, style_function=style_function, name=name) gj.add_to(mapMT) # Add streamflow stuff pntsStream = r'../data/streamflow/MT_active_gages.geojson' with open(pntsStream) as f: stmGauges = json.load(f) snotel_cluster = flm.MarkerCluster().add_to(mapMT) for feats in (stmGauges['features']): lon, lat = feats['geometry']['coordinates'] id = feats['properties']['STAID'] icon = flm.Icon(icon='ok') try: with open('../graphs/'+id+'.html', 'r') as f: if (EMBED_HTML): html = f.read() else: html = 'graphs/'+id+'.html' except IOError: continue
def mapWithMarkerCluster(map, name): markerCluster = folium.MarkerCluster(name).add_to(map) return markerCluster
station_locations = [Point(xy) for xy in zip(divvy_data["FROM LONGITUDE"], divvy_data["FROM LATITUDE"])] geo_stations = gpd.GeoDataFrame(divvy_data, geometry = station_locations) geo_stations.crs = fiona.crs.from_epsg(3528) geo_stations.set_geometry(geo_stations.buffer(0.002), inplace = True) crimes = pd.read_csv("chicago_crimes.csv", usecols = [5, 19, 20]) crimes.dropna(inplace = True) crime_locations = [Point(xy) for xy in zip(crimes["Longitude"], crimes["Latitude"])] geo_crimes = gpd.GeoDataFrame(crimes, geometry = crime_locations) geo_crimes.crs = fiona.crs.from_epsg(3528) result = gpd.sjoin(geo_crimes, geo_stations) result['Counts'] = result.groupby("index_right")["FROM STATION ID"].transform('count') result = result[["Primary Type","FROM STATION ID", "FROM STATION NAME", "FROM LONGITUDE","FROM LATITUDE", "Counts"]] result.to_csv('join_data.csv') result = result[["FROM STATION ID", "FROM STATION NAME", "FROM LONGITUDE","FROM LATITUDE", "Counts"]].drop_duplicates(keep='first') # create empty map zoomed in on Chicago Chi_COORDINATES = (41.88, -87.63) chi_map = folium.Map(location=Chi_COORDINATES, zoom_start=12) #when zoom out, cluster and sum the number my_marker_cluster = folium.MarkerCluster().add_to(chi_map) # add a marker for every station, use a clustered view. for ix, row in result.iterrows(): text = "Station Name: " + row['FROM STATION NAME'] + "<br>" + "Station Id: " + str(row['FROM STATION ID']) + "<br>" \ + "Crime Count: " + str(row['Counts']) popup = folium.Popup(IFrame(text, width=300, height=100)) folium.Marker(location = [row['FROM LATITUDE'],row['FROM LONGITUDE']], popup=popup).add_to(my_marker_cluster) chi_map.save('divvy_crime_map.html')
def map_create(df_sen, latlon): #latlon= pd.read_csv('files/us_lat_lon.csv') width, height = 550, 500 # CREATE MAP: sen_map = folium.Map(location=[40, -115], zoom_start=3, tiles='Stamen Terrain', width=width, height=height) # CLUSTER POINTS marker_cluster = folium.MarkerCluster().add_to(sen_map) #inline_map(radars) for row in range(len(latlon)): state_name = latlon['state_name'][row] state = latlon['state'][row] lon = latlon['lon'][row] lat = latlon['lat'][row] df = df_sen.loc[df_sen['State'] == state] for row in df.index: if df['Party'][row] == 'R': color = "red" elif df['Party'][row] == 'D': color = "blue" elif df['Party'][row] == 'I': color = 'green' else: color = 'black' html = """ <h1>{}</h1> <table style="width:100%"> <tr, td aling="center"> <th>First</th> <th>Last</th> <th>Party</th> <th>Yea</th> <th>Nay</th> <th>No vote</th> <th>Total</th> </tr> <tr> <td align="center">{}</td> <td align="center">{}</td> <td align="center">{}</td> <td align="center">{}</td> <td align="center">{}</td> <td align="center">{}</td> <td align="center">{}</td> </tr> </table> """ html = html.format(state_name, df['First'][row], df['Last'][row], df['Party'][row], df['Yea'][row], df['Nay'][row], df['Not Voting'][row], df['Total'][row]) iframe = IFrame(html=html, width=400, height=125) popup = folium.Popup(iframe, max_width=2650) icon = folium.Icon(color=color, icon='circle') folium.Marker( (lat, lon), popup=popup, icon=icon, ).add_to(marker_cluster) return sen_map
def parse_full_date(row): date = datetime.datetime.strptime(row["date_of_stop"], "%Y-%m-%dT%H:%M:%S") time = row["time_of_stop"].split(":") date = date.replace(hour=int(time[0]), minute=int(time[1]), second = int(time[2])) return (datestops["date"] = stops.apply(parse_full_date, axis=1) #We can now make a plot of which days result in the most traffic stops: import matplotlib.pyplot as plt %matplotlib inline plt.hist(stops["date"].dt.weekday, bins=6) plt.show() #In this plot, Monday is 0, and Sunday is 6. It looks like Sunday has the most #stops, and Monday has the least. This could also be a data quality issue where #invalid dates resulted in Sunday for some reason. You'll have to dig more #deeply into the date_of_stop column to figure it out definitely. #We can also plot out the most common traffic stop times: plt.hist(stops["date"].dt.hour, bins=24) plt.show() #It looks like the most stops happen around midnight, and the fewest happen #around 5am. This might make sense, as people are driving home from bars and #dinners late at night, and may be impaired. This may also be a data quality #issue, and poking through the time_of_stop column will be necessary to get the #full answer. #Subsetting the stops #Now that we've converted the location and date columns, we can map out the #traffic stops. Because mapping is very intensive in terms of CPU resources and #memory, we'll need to filter down the rows we use from stops first: last_year = stops[stops["date"] > datetime.datetime(year=2018, month=7, day=25)] #In the above code, we selected all of the rows that came in the past year. We #can further narrow this down, and select rows that occured during rush hour -- #the morning period when everyone is going to work: morning_runs = last_year[(last_year["date"].dt.weekday < 5) & (last_year["date"].dt.hour > 5) & (last_year["date"].dt.hour < 10)] #Using the excellent folium package, we can now visualize where all the stops #occured. Folium allows ou to easily create interactive maps in Python by #leveraging leaflet. In order to perserve performance, we'll only visualize #the first 1000 rows of morning_rush: import folium from folium import plugins stops_map = folium.Map(location=[39.0836, -77.1483], zoom_start=11) marker_cluster = folium.MarkerCluster().add_to(stops_map) for name, row in morning_rush.iloc[:1000].iterrows(): folium.Marker([row["longitude"], row["latitude"]], popup=row["description"]) .add_to(marker_cluster) stops_map.create_map('stops.html')stops_map #This shows that many traffic stops are concentrated around the bottom right #of the country. We can extend our analysis further with a heatmap: stops_heatmap = folium.Map(location=[39.0836, -77.1483], zoom_start=11)stops_heatmap.add_children(plugins.HeatMap([[row["longitude"], row["latitude"]] for name, row in morning_rush.iloc[:1000].iterrows()])) stops_heatmap.save("heatmap.html")stops_heatmap
# -*- coding: utf-8 -*- """ Created on Thu Dec 15 22:04:50 2016 @author: tud52132 """ import folium import folium.plugins import pandas as pd PHILLY_COORDINATES = (40.010011, -75.136214) crimedata = pd.read_csv(r'C:\Data\incident.csv') crime_map = folium.Map(location=PHILLY_COORDINATES, zoom_start=12) marker_cluster = folium.MarkerCluster().add_to(crime_map) for name, row in crimedata[0:MAX_RECORDS].iterrows(): folium.Marker([row["Y"], row["X"]], popup=row["Time"]).add_to(marker_cluster) crime_map.save('crimemap1.html') crime_heatmap = folium.Map(location=PHILLY_COORDINATES, zoom_start=12) crime_heatmap.add_children( folium.plugins.HeatMap( [[row["Y"], row["X"]] for name, row in crimedata[0:MAX_RECORDS].iterrows()])) crime_heatmap.save("heatmap.html") crime_heatmap
map_osm.save('sf_bike.html') map_osm # In[122]: count_start_station = pd.read_csv("Count Start Station with lat lng.csv") count_start_station = count_start_station[ count_start_station.lat != 37.779280799999995] #count_start_station # In[ ]: # In[128]: marker_cluster = folium.MarkerCluster("Cluster Name").add_to(map_osm) for station, row in count_start_station.iterrows(): #print row['NaicsDescription'] folium.CircleMarker(location=[row['lat'], row['lng']], radius=row['Count'] / 100, color='red', fill_color='red', popup=str(row['Start Station']) + " | Nnumber of bikes borrowed: " + str(row['Count'])).add_to(marker_cluster) #for index,row in subset.iterrows(): # folium.CircleMarker(location=[row['lat'],row['lng']],radius=200,popup=row['NaicsDescription'],color='#3186cc').add_to(marker_cluster) #for i in range(len(lats)): # folium.CircleMarker(location=[subset[i]['lat'],subset[i]['lng']],radius=200,popup=subset[i]['NaicsDescription'],color='#3186cc').add_to(marker_cluster)
nyc_taxi_may_dec2015['tpep_dropoff_datetime']) ########################Basic plot done############################## ########################################################################## #################### nyc_taxi_may_dec2015 pickup ################################### NY_COORDINATES = (40.773124694800003, -73.952171325699993) # for speed purposes MAX_RECORDS = 1000 # create empty map zoomed in on New York nyc_taxi_may_dec2015_pickup = folium.Map(location=NY_COORDINATES, zoom_start=12) marker_cluster = folium.MarkerCluster("Pickups").add_to( nyc_taxi_may_dec2015_pickup) #add a marker for every record in the filtered data, use a clustered view for each in nyc_taxi_may_dec2015[0:MAX_RECORDS].iterrows(): folium.Marker([each[1]['pickup_latitude'],each[1]['pickup_longitude']])\ .add_to(marker_cluster) nyc_taxi_may_dec2015_pickup.create_map(path='nyc_taxi_may_dec2015_pickup.html') #folium.TileLayer('nyc_taxi_may_dec2015_pickup').add_to(nyc_taxi_may_dec2015_pickup) #folium.LayerControl().add_to(nyc_taxi_may_dec2015_pickup) #################### nyc_taxi_may_dec2015 dropff ################################### # create empty map zoomed in on New York nyc_taxi_may_dec2015_dropff = folium.Map(location=NY_COORDINATES, zoom_start=12) marker_cluster = folium.MarkerCluster("Dropoff").add_to(
#mapfile = 'test_mpleaflet.html' #mplleaflet.show(fig=f2,path=mapfile, tiles='mapbox bright') mapfile = 'test_mpleaflet2.html' mplleaflet.show(fig=f2, path=mapfile) ### nicer print ' Plot folium map ...' width, height = 1200, 800 map = folium.Map(location=[42, -102], zoom_start=3, tiles='OpenStreetMap', width=width, height=height) marker_cluster = folium.MarkerCluster().add_to(map) print('Map EPA pm10 obs ...') for i in epa_ind_pm10: folium.Marker( location=[epa_pm10_locs['lat'][i], epa_pm10_locs['lon'][i]], popup='EPA PM10 (' + str(epa_pm10_locs.Name[i]) + ')', #icon = epa_ic icon=folium.Icon(color='blue', icon_color='white')).add_to(marker_cluster) for i in epa_ind_pm25: folium.Marker( location=[epa_pm25_locs['lat'][i], epa_pm25_locs['lon'][i]], popup='EPA pm25 (' + str(epa_pm25_locs.Name[i]) + ')', #icon = epa_ic icon=folium.Icon(color='blue',
from folium.plugins import MarkerCluster import folium from folium import plugins #load King County datasets crimes = pd.read_csv('../King_County_Sheriff_s_Office.csv') houses = pd.read_csv("../kc_house_data.csv", parse_dates=['date']) #prepare base map '''Use mean of latitude and longitude in dataset and set original zoom''' kingcounty_map = folium.Map( location=[houses['lat'].mean(), houses['long'].mean()], zoom_start=10) kingcounty_map.save('kingcounty_map.html') #group together houses house_groups = folium.MarkerCluster().add_to(kingcounty_map) '''Iterate through rows and create marker clusters. popup datatypes: price: float64 size: int64 year built: int64''' for name, row in houses[0:200].iterrows(): folium.Marker([row["lat"], row["long"]], popup="Price: {0}$, Size: {1} sqft,Year Built: {2}"\ .format(row["price"], row['sqft_living'], row['yr_built'])).add_to(house_groups) #save output of house markers kingcounty_map.save('houses_map.html') '''Create new basemap for crimes heat map''' kccrimes_heatmap = folium.Map(
def nearby_map(self, result, lat, lng): l_list = result[['geometry.location.lat', 'geometry.location.lng']].values.tolist() p_list = result['text'].values.tolist() k_list = result['keyword'].values.tolist() dd_list = result[['name', 'distance', 'travelTime']].values.tolist() SF_COORDINATES = (float(lat), float(lng)) blr = folium.Map(location=SF_COORDINATES, tiles='Cartodb dark_matter', attr='osm', zoom_start=16, control_scale=True) html = """<html> <body> <h2>Traffic Level in surrounding Roads</h2> <table> {0} </table> </body> </html>""" items = self.cong_source(lat, lng, 200) tr = "<tr>{0}</tr>" td = "<td>{0}</td>" subitems = [ tr.format(''.join([td.format(a) for a in item])) for item in items ] html1 = html.format("".join(subitems)) te = folium.Html(html1, script=True) popup = folium.Popup(te, max_width=2650) distance = [] for each, p, k in zip(l_list, dd_list, k_list): distance = distance + [math.ceil(p[2] / 60)] distance.sort() marker_cluster = folium.MarkerCluster("Emergency cluster").add_to(blr) #Marker Cluster for each, p, k in zip(l_list, dd_list, k_list): if k == 'hospital': folium.Marker(each, popup=p[0] + ',distance = ' + str(p[1]) + "meters, travel time = " + str(math.ceil(p[2] / 60)) + "mins", icon=folium.Icon( color='green', icon='plus-sign')).add_to(marker_cluster) else: folium.Marker(each, popup=p[0] + ',distance = ' + str(p[1]) + "meters, travel time = " + str(math.ceil(p[2] / 60)) + "mins", icon=folium.Icon( color='blue', icon='hdd')).add_to(marker_cluster) folium.Marker([float(lat), float(lng)], popup='incident point', icon=folium.Icon(color='red', icon='warning-sign')).add_to(blr) #Polyline for index, row in result.iterrows(): print(row['route']) dic = json_normalize(row['route']) a = dic[['position.latitude', 'position.longitude']].values.tolist() folium.PolyLine(a, color="red", weight=2.5, opacity=1).add_to(blr) #blr.save('/home/raghuram/Documents/RaghuProjects/datamodels/map1.html') return blr
import folium import pandas as pd andorra = pd.read_csv("andorraCities.csv") path = "/Users/javierzarate/Desktop/andorra/projects/maps/2016-07-27/2016-07-27_0_hour.csv" path_1 = "prueba.csv" agent = pd.read_csv(path_1) map_1 = folium.Map(location=[42.5, 1.5], zoom_start=12, tiles='Stamen Terrain') andorraCitiesCluster = [] andorraCities = [] for each in andorra.iterrows(): andorraCitiesCluster.append( folium.MarkerCluster(each[1]["name"]).add_to(map_1)) andorraCities.append([each[1]["name"], each[1]["lat"], each[1]["lon"]]) # print andorraCitiesCluster[0], andorraCities[0] for each in agent.iterrows(): folium.Marker([each[1]["lat"], each[1]["lon"]], popup=each[1]["name"]).add_to(andorraCitiesCluster[1]) map_1.save('cluterMap.html')