def build_html_for(execution_date, conn, credentials): sql_query = build_query_for(execution_date.year, execution_date.month) logging.info(sql_query) df = sqlio.read_sql_query(sql_query, conn) if df.empty: logging.info('Query returned empty results set') return pickup_map = Map( location=[df['pickup_latitude'].mean(), df['pickup_longitude'].mean()], tiles='OpenStreetMap', zoom_start=12) mc = MarkerCluster() for row in df.itertuples(): mc.add_child( folium.Marker(location=[row.pickup_latitude, row.pickup_longitude], popup=str(row.pickup_latitude) + ',' + str(row.pickup_longitude))) pickup_map.add_child(mc) html_file_name = "{}-{}_pickups_map.html".format(execution_date.year, execution_date.month) pickup_map.save(outfile=html_file_name) upload_file_to_s3( html_file_name, "data-sprints-eng-test/outputs/monthly/{}".format(html_file_name), credentials, "text/html") os.remove(html_file_name)
def produce_map(year): """ This function generates a map of the US and displays all the data for a given year in popups and a color gradient """ year_file = yearly_map(year) state_geo = os.path.join('data', 'us_states.json') state_data = pd.read_csv(year_file) marker_year = 'StateLonandLat'+str(year)+'.csv' marker_data = os.path.join('data',marker_year) marker_coord = pd.read_csv(marker_data) #establishes the center of map based on longitude and latitude m = Map(location=[50.246366, -110], zoom_start=4) #sets the color scheme, data used for legend, and legend labels Choropleth(geo_data=state_geo,name='choropleth',data=state_data, columns=['State', 'Death Rate'], key_on='feature.id', fill_color='BuPu', fill_opacity=0.7, line_opacity=0.5, legend_name='Average Death Rate in '+str(year) ).add_to(m) #create markers and places them within corresponding state for i in range(0,len(marker_coord)): #popup contains data about causes fo death popup = Popup(marker_coord.iloc[i]['state'],max_width=350) Marker([marker_coord.iloc[i]['lon'],marker_coord.iloc[i]['lat']], popup=popup).add_to(m) LayerControl().add_to(m) map = str(year)+'.html' m.save(map) webbrowser.open('file://'+os.path.realpath(map))
def create_map(df_collisions, df_stations, boroughs): geo_map = Map(location=[40.74527, -73.988573], tiles=None, zoom_start=12, control_scale=True) close_distance = 200 # meters # collisions TileLayer('Stamen Terrain', name='Collision Data').add_to(geo_map) for borough in boroughs: feature_group = FeatureGroup(name=borough.capitalize()) marker_cluster = MarkerCluster().add_to(feature_group) df_collisions[df_collisions['borough'] == borough].apply( lambda r: Marker( location=[r['latitude'], r['longitude']], tooltip=f"{r['cyclist_injured'] + r['cyclist_killed']} cyclists injured/killed", icon=Icon(color='darkblue', icon='exclamation-circle', prefix='fa')).add_to(marker_cluster), axis=1) feature_group.add_to(geo_map) # bike stations quartiles = df_stations['close_collisions'].quantile([0.25, 0.5, 0.75]).tolist() feature_group = FeatureGroup(name='Bike Stations') df_stations.apply(lambda r: CircleMarker( location=(r['latitude'], r['longitude']), radius=2, color=get_color(r['close_collisions'], quartiles), tooltip=f"Bike Station {int(r['id'])}: {int(r['close_collisions'])} collisions within {close_distance}m", fill=True).add_to(feature_group), axis=1) feature_group.add_to(geo_map) LayerControl(collapsed=False).add_to(geo_map) geo_map.save('templates/map.html')
def multi_map(input_file): os.chdir(geomap_root) # Check if Geolite file exists geolite_check() file_path = os.path.abspath(os.pardir) input_file = f"{file_path}/{input_file}" with open(input_file) as f: line = [line.strip() for line in f.readlines()] ip_map = Map([40, -5], tiles="OpenStreetMap", zoom_start=3) try: geo_reader = geoip2.database.Reader("GeoLite2-City.mmdb") for addr in line: response = geo_reader.city(addr) if response.location: logger.success(f"[+] Mapping {addr}") lat = response.location.latitude lon = response.location.longitude Marker([lat, lon], popup=addr).add_to(ip_map) ip_map.save("multi_map.html") except ValueError as err: print(f"[error] {err}") except geoip2.errors.AddressNotFoundError: logger.warning("[-] Address is not in the geoip database.") except FileNotFoundError: geolite_check()
class Mapper: def __init__(self, targets: list): self.targets = targets self._generate_map() def _get_coordinates(self, target) -> list: url = F"http://ip-api.com/json/{target}?fields=lat,lon" resp = get(url) resp_json = loads(resp.text) latitude, longitude = resp_json["lat"], resp_json["lon"] return [latitude, longitude] def _generate_map(self): # creating map self.m = Map(location=[0,0], zoom_start=3) def add_target_marker(self, target): # adding marker to map Marker( location=self._get_coordinates(target), popup=target, icon=Icon() ).add_to(self.m) def save(self): # save to html file self.m.save("./map.html") print(bold(blue("Map saved to file:")), "./map.html")
def save_map(date): valencia = [39.4561165311493, -0.3545661635] mapa = Map(location=valencia, tiles='OpenStreetMap', zoom_start=10) GeoJson(open('voronoi.json'), name='Diagrama de Voronoi').add_to(mapa) GeoJson(open('estaciones_de_recarga_' + date + '.json'), name='Estaciones de Recarga').add_to(mapa) LayerControl().add_to(mapa) mapa.save('valencia_' + date + '.html')
def get_beds(): df = get_df() _map = Map(location=[41.8781, -87.6298], tiles='cartodbpositron', zoom_start=10) for idx, row in df.iterrows(): Marker([row['Y'], row['X']], popup=row['HOSPITAL_NAME']).add_to(_map) _map.save('templates/all_beds.html')
def generate_web_map_html(filename: str) -> None: map = Map(location=[48.7767982, -121.8109970]) volcanoes_feature_group = get_volcanoes_feature_group() population_feature_group = get_population_feature_group() map.add_child(volcanoes_feature_group) map.add_child(population_feature_group) map.add_child(LayerControl()) map.save(filename)
def gen_map(self): # read database connection = sqlite3.connect("posts.db") cursor = connection.cursor() sql = f"""SELECT * FROM "{self.handle}" """ cursor.execute(sql) result = cursor.fetchall() connection.close() # Generate map, cluster class and create empty coordinates list if self.handle == "4x4theboiz": my_map = Map(location=[-25.25, 21.2], zoom_start=5) elif self.handle == "teampolarsteps": my_map = Map(location=[52.35, 5.3], zoom_start=9) elif self.handle == "cityofcapetown": my_map = Map(location=[-34.1, 18.420], zoom_start=10) elif self.handle == "backpackingtours": my_map = Map(location=[10, 100], zoom_start=3) elif self.handle == "tony_ontheroad": my_map = Map(location=[38.5, -2.75], zoom_start=6) elif self.handle == "rolling_sloane": my_map = Map(location=[55, 2.64], zoom_start=4) elif self.handle == "cape_secrets": my_map = Map(location=[-33.4, 18.8], zoom_start=8) else: my_map = Map(location=[0, 0], zoom_start=2) mc = MarkerCluster() coords = [] # For each location convert address to coordinates, create popup and marker, # add to marker cluster for i in range(0, len(result), 1): popup_content = f"{result[i][0]} <br> " \ f"<a href={result[i][1]} > See Post" p = Popup(popup_content, max_width=400) mk = Marker([result[i][2], result[i][3]], p) mc.add_child(mk) lat_lon = (result[i][2], result[i][3]) coords.append(lat_lon) # Add Polyline with coords if self.handle == "4x4theboiz": polyline = PolyLine(coords, color="red", weight=2, opacity=0.7) polyline.add_to(my_map) elif self.handle == "tony_ontheroad": polyline = PolyLine(coords, color="red", weight=2, opacity=0.7) polyline.add_to(my_map) else: pass # Add Marker Cluster with mc my_map.add_child(mc) # Save the Map Instance Into a HTML file map_name = f"templates/map_{self.handle}.html" my_map.save(map_name)
def save(mape: folium.Map, path: str): """fct qui save et open une map""" assert isinstance(mape, folium.Map), "mape must a folium.Map, not {}" \ .format(type(mape)) assert isinstance(path, str), "path must be a str, not {}" \ .format(type(path)) mape.save(path) webbrowser.open(path)
def get_beds_utilization_rate(): df = get_df() _map = Map(location=[41.8781, -87.6298], tiles='cartodbpositron', zoom_start=10) for i in range(0, len(df)): Circle(location=[df.iloc[i]['Y'], df.iloc[i]['X']], radius=10000, fill=True, color=color(df.iloc[i]['BED_UTILIZATION'])).add_to(_map) _map.save('templates/bed_utilization_rate.html')
def map_multiple_outputs_points(directory: str, map_center=None, save_path=None): """ Creates a folium map of single or multiple outputs from the LP model. Circle markers communicate both location of station and forecast demand (diameter). Good for outputs from LP model that outputs points - not hexes. """ station_locations = open_station_locations() if not map_center: m_lat = station_locations[:1]['latitude'] m_long = station_locations[:1]['longitude'] else: m_lat = map_center[0] m_long = map_center[1] m = Map( location=[m_lat, m_long], tiles='cartodbpositron', zoom_start=9 ) colors = ['blue', 'crimson', 'violet', 'orange', 'yellow', 'black'] cnt = 0 for file in os.listdir(directory): open_path_1 = f'data/GIS/LP_outputs/{file}' print(file) name = file.rstrip('.csv') proposed_stations_1 = open_lp_proposed_stations(lp_proposed_stations_path=open_path_1) proposed_stations_1.set_index('id', inplace=True) proposed_stations_1 = join_dfs(station_locations, proposed_stations_1) feature_group = FeatureGroup(name=name) for i, row in proposed_stations_1.iterrows(): if row['demand'] == 0: pass else: c = CircleMarker( radius=row['demand'], location=[row["latitude"], row["longitude"]], tooltip=f"Station ID: {row.name} \n Demand: {row['demand']} kWh", color=colors[cnt], fill=True, fill_color=colors[cnt] ) c.add_to(feature_group) feature_group.add_to(m) cnt += 1 LayerControl('bottomright', collapsed=False).add_to(m) if save_path: m.save(save_path) return m
def generateHeatmaps(df_date_list, date_columns): for date_values, date_col in zip(df_date_list, date_columns): base_map = Map(location=default_location, control_scale=True, zoom_start=default_zoom_start) heatmap = HeatMap(data=date_values, name='Confirmed cases', min_opacity=0.6, radius=10, max_zoom=13) heatmap.add_to(base_map) base_map.save(f"./heatmaps/heatmap_{date_col.replace('/', '_')}.html")
def index(): if request.method == 'POST': #utilisation de la methode POST pour validation. msg = request.form[ 'valeur'] #la variable msg prend comme valeur l'url rentré ip4 = socket.gethostbyname(msg) #affichage de l'ipv4 sta = geocoder.maxmind( ip4) #la variable sta prend comme valeur l'url rentré sta1 = sta.json asn1 = IPDetailsCache() #instanciation de la classe IPDetailsCache() asn1_1 = asn1.GetIPInformation( ip4) #utilisation de la methode GetIPInformation() wh = IPWhois(str(ip4)) #utilisation de la methode GetIPInformation() wh1 = wh.lookup_whois( get_referral=True) #utilisation de la methode GetIPInformation() son_r = msg.replace('www.', '') repnse = dns.resolver.query( son_r, 'MX' ) #on obtient tout les serveurs de messagerie possible de notre domaine contenu = dns.resolver.query( son_r, 'NS') #on obtient tout les serveurs DNS possible de notre domaine url = urllib2.urlopen( "http://{0}".format(son_r) ) #on ouvre notre url grace a la methode urlopen du module urllib2 url_result = dict( url.info() ) #recuperation de toute les reponse HTTP possible sur en provenance du serveur dat_a = google(str(msg)) carto = Map(location=[dat_a.lat, dat_a.lng], zoom_start=15) Marker([dat_a.lat, dat_a.lng], popup=str(msg)).add_to(carto) carto.save('templates/cartographie.html') return render_template('resultat.html', ip4=ip4, msg=msg, sta1=sta1, asn1_1=asn1_1, wh1=wh1, repnse=repnse, contenu=contenu, url_result=url_result) return render_template("acceuil.html") #affichage de la page d'acceuil
def draw_map(file_name: str): m = Map( location=[38.319907, 26.639365], attr= 'Data from <a href="https://openflights.org/data.html">Openflight</a> using Folium and Leaflet.js', zoom_start=15.6) TileLayer( 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}{r}.png', attr= '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> Project Laika' ).add_to(m) add_markers(m, file_name) m.save("map.html")
def routeBuild(self): map = Map(self.coordList[0], zoom_start=9) popup_str = "Широта:{0:3f} Долгота:{1:3f}" lat1, lon1 = self.coordList[0] lat2, lon2 = self.coordList[len(self.coordList) - 1] PolyLine(self.coordList, color="red", weight=3, opacity=1).add_to(map) Marker([lat1, lon1], popup=popup_str.format(lat1, lon1), icon=Icon(color="blue")).add_to(map) Marker([lat2, lon2], popup=popup_str.format(lat2, lon2), icon=Icon(color="green")).add_to(map) map.save("map.html")
def part_1(data): # These are the users we are interested in users = [75027, 102829] users_data = data.loc[data['User_ID'].isin(users)] users_data['timestamp'] = 0 # Convert the date to a timestamp so it may be visualised users_data['timestamp'] = users_data['date'].apply(lambda x: time.mktime( datetime.datetime.strptime(x, '%d/%m/%Y').timetuple()) - np.min( users_data['timestamp'])) # Dict to store user geoms user_points = {} # Loop through users and store their [lat, lon, timestamp] in the dict for i in users: user_data = users_data.loc[users_data['User_ID'] == i] user_points[i] = [ i for i in zip(user_data['lat'], user_data['lon'], users_data['timestamp']) ] # Set up a colormap so the timestamp can be visualised colormap = cm.LinearColormap(colors=['red', 'blue'], index=[ np.min(users_data['timestamp']), np.max(users_data['timestamp']) ], vmin=np.min(users_data['timestamp']), vmax=np.min(users_data['timestamp'])) # Initialise the map object my_map = Map([np.mean(data['lat']), np.mean(data['lon'])], zoom_start=12.5) # Colour for each user colors = ['green', 'orange'] # Loop through each user in the dict for i, (k, v) in enumerate(user_points.items()): color = colors[i] # Loop through the points/timestamps for p in v: folium.Circle(location=p[0:2], radius=80, fill=True, fill_color=color, color=colormap(p[2]), fill_opacity=1).add_to(my_map) my_map.save('my_map_1_1.html')
def draw_refuse_routes_map(self, refuse_routes_file_path: string = 'resource/data/Hav_Refuse_Routes_WGS84' '/Hav_Refuse_Routes_WGS84.json'): geo_map = Map(location=[42.795390191429625, -71.07516023514027], zoom_start=12) data = self.preprocess.get_refuse_routes_data(refuse_routes_file_path) keys_pool = [ 'MONDAY - Red Week', 'TUESDAY - Red Week', 'WEDNESDAY - Red Week', 'THURSDAY - Red Week', 'FRIDAY - Red Week', 'MONDAY - Blue Week', 'TUESDAY - Blue Week', 'WEDNESDAY - Blue Week', 'THURSDAY - Blue Week', 'FRIDAY - Blue Week', 'MERCANTILE - Every Friday' ] for key in keys_pool: feature_group = FeatureGroup(name=key, show=True) if key.endswith('Red Week'): color = 'red' elif key.endswith('Blue Week'): color = 'blue' else: color = 'black' for each in data[key]: geo_json = GeoJson( data=each, style_function=lambda feature, color=color: { 'fillColor': '#A9A9A9', 'color': color, 'weight': 3, }, highlight_function=lambda feature, color=color: { 'fillColor': '#FFBFFF', 'color': color, 'weight': 4, }, tooltip=key, overlay=True ) geo_json.add_to(feature_group) feature_group.add_to(geo_map) LayerControl().add_to(geo_map) cur_time = time.strftime('%m_%d_%Y_%H_%M_%S', time.localtime()) file_name = 'refuse_routes_{}.html'.format(cur_time) geo_map.save(os.path.join(self.refuse_routes_directory_path, file_name))
def map_free_geo(QRY): ip_map = Map([40, -5], tiles='OpenStreetMap', zoom_start=3) try: response = f'https://freegeoip.live/json/{QRY}' req = requests.get(response) if req.status_code == 200: data = json.loads(req.content.decode('utf-8')) lat = data['latitude'] lon = data['longitude'] Marker([lat, lon], popup=QRY).add_to(ip_map) ip_map.save(ip_map_file) else: req.raise_for_status() except Exception as err: logger.warning(f"[error] {err}\n")
def map_free_geo(QRY): ip_map = Map([40, -5], tiles="OpenStreetMap", zoom_start=3) freegeoip = f"https://freegeoip.live/json/{QRY}" try: req = requests.get(freegeoip) req.raise_for_status() except ConnectionError as err: logger.warning(f"[error] {err}\n") else: if req.status_code == 200: data = json.loads(req.content.decode("utf-8")) lat = data["latitude"] lon = data["longitude"] Marker([lat, lon], popup=QRY).add_to(ip_map) ip_map.save(ip_map_file)
def heatfromdoc(doc): import networkx as nx import osmnx as ox from folium import Map import folium.plugins as plugins ox.config(use_cache=True, log_console=True) G = ox.graph_from_place('Cologne', network_type='bike') gdf_nodes, gdf_edges = ox.graph_to_gdfs(G) timestamps = [] for row in doc: timestamps.append(row["starttime"]) timestamps = list(sorted(timestamps)) datapoints = [] cnt = 0 timeindex = [] points = [] for time in timestamps: for route in doc: try: if route["starttime"] == time: for node in route["route"]: point = [] nodepoint = gdf_nodes.loc[node] point = [nodepoint["y"], nodepoint["x"], 1] points.append(point) except: continue if cnt == 6: cnt = 0 if points != [] and cnt == 0: datapoints.append(points) timeindex.append(str(time)) points = [] cnt += 1 m = Map([50.9287107, 6.9459497], tiles="cartodbpositron", zoom_start=13) hm = plugins.HeatMapWithTime(datapoints, index=timeindex, auto_play=True, max_opacity=0.5, radius=8, use_local_extrema=True) hm.add_to(m) m.save('index.html')
def main(args): if not args.output[-5:] == '.html': exit('ERROR Output file must be .html') heatmap_data = [] for gpx_file in get_gpx_files(args): if not args.quiet: print('Reading {}'.format(gpx_file)) with open(gpx_file, 'r') as file: last_point = None for line in file: if '<trkpt' in line: r = re.findall('[-]?[0-9]*[.]?[0-9]+', line) point = [float(r[0]), float(r[1])] if last_point is not None and distance(point, last_point) < args.skip_distance: continue heatmap_data.append(point) last_point = point if not args.quiet: print('Loaded {} trackpoints'.format(len(heatmap_data))) fmap = Map(tiles = 'CartoDB positron' if args.light_map else 'CartoDB dark_matter', location=args.center, zoom_start=11, prefer_canvas = True, max_zoom = HEATMAP_MAXZOOM) HeatMap(heatmap_data, radius = args.radius, blur = args.blur, gradient = HEATMAP_GRAD['light' if args.light_map else 'dark'], min_opacity = args.min_opacity, max_val = args.max_val).add_to(fmap) if args.center is None: fmap.fit_bounds(fmap.get_bounds()) fmap.save(args.output) if not args.quiet: print('Saved {}'.format(args.output)) if not args.quiet: webbrowser.open(args.output, new = 2, autoraise = True)
def create_map(self): """ Creates a map of earthquakes. """ map1 = Map(tiles="Stamen Terrain") for i in self.locations: if self.place_damaged[i[0], i[1]] and self.place_damaged[i[0], i[1]] > 0.5: if self.place_damaged[i[0], i[1]] > 5\ : a = 'darkred' to_write = 'The earthquake damage here is really high.' elif self.place_damaged[i[0], i[1]] > 3.5: a = 'red' to_write = 'Might cause some destructions.' elif self.place_damaged[i[0], i[1]] > 1.5: a = 'orange' to_write = "Some ground shaking but would't cause some big troubles" else: a = 'yellow' to_write = "Almost nothing changed, but probably make some inconvenience to people" if len(self.date) == 1: sized = 4 elif len(self.date) == 2: sized = 50 elif len(self.date) == 3: sized = 1500 map1.add_child( Circle(location=[i[1], i[0]], popup=to_write, radius=10000 + sized * self.locations[i[0], i[1]], color=a, fill=True, fill_color=a)) map_name = "templates/Map_" + str(int(self.date[0])) if len(self.date) >= 2: map_name += '_' + str(int(self.date[1])) if len(self.date) == 3: map_name += "_" + str(int(self.date[2])) map_name += '.html' map1.save(map_name)
def map_maxmind(QRY): try: geo_reader = geoip2.database.Reader(gl_file) ip_map = Map([40, -5], tiles='OpenStreetMap', zoom_start=3) response = geo_reader.city(QRY) if response.location: lat = response.location.latitude lon = response.location.longitude popup = Popup(QRY) Marker([lat, lon], popup=popup).add_to(ip_map) ip_map.save(ip_map_file) except geoip2.errors.AddressNotFoundError: logger.warning(f"[-] Address {QRY} is not in the geoip database.") except FileNotFoundError: logger.info(f"\n[*] Please download the GeoLite2-City database file: ") print(" --> https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz") time.sleep(2)
class Maps(): def __init__(self, lat, lon, **kwargs): # two coords point self.lat = lat self.lon = lon self.save_location = kwargs.pop('save', 'template/map.html') self.file = self.save_location.split('/')[-1] self.maps = Map(location=[self.lat, self.lon], **kwargs) def save(self): self.maps.save(self.save_location) def marker(self, **kwargs): add_to = kwargs.pop('add_to', True) marker = Marker([self.lat, self.lon], **kwargs) if add_to: marker.add_to(self.maps)
def main(args): if not args.output[-5:] == '.html': exit('ERROR Output file must be .html') heatmap_data = [] for gpx_file in get_gpx_files(args): if not args.quiet: print('Reading {}'.format(gpx_file)) with open(gpx_file, 'r') as file: for line in file: if '<trkpt' in line: r = re.findall('[-]?[0-9]*[.]?[0-9]+', line) heatmap_data.append([float(r[0]), float(r[1])]) if not args.quiet: print('Loaded {} trackpoints'.format(len(heatmap_data))) if args.skip_ratio > 1: heatmap_data = heatmap_data[::args.skip_ratio] print('Reduced to {} trackpoints'.format(len(heatmap_data))) fmap = Map(tiles = 'CartoDB positron' if args.light_map else 'CartoDB dark_matter', prefer_canvas = True, max_zoom = HEATMAP_MAXZOOM) HeatMap(heatmap_data, radius = args.radius, blur = args.blur, gradient = HEATMAP_GRAD['light' if args.light_map else 'dark'], min_opacity = args.min_opacity, max_val = args.max_val).add_to(fmap) fmap.fit_bounds(fmap.get_bounds()) fmap.save(args.output) if not args.quiet: print('Saved {}'.format(args.output)) webbrowser.open(args.output, new = 2, autoraise = True)
def folium(dest="docs/folium.html"): """ genreate folium.html """ my_map = Map( location=[43.0645597, 141.3481196], zoom_start=10, width="100%", height="90%", tiles="openstreetmap", ) marker_cluster = MarkerCluster() for _, row in df.iterrows(): lat = row["緯度"] lng = row["経度"] name = row["施設名"] address = row["検索用住所"] data_type = row["データ区分"] popup_html = f""" <h1>{name}</h1> <h2>{address}</h2> <table> <tbody> <tr> <th>緯度</th> <td>{lat}</td> </tr> <tr> <th>経度</th> <td>{lng}</td> </tr> <tr> <th>データ区分</th> <td>{data_type}</td> </tr> </tbody> </table> """ popup = Popup(IFrame(popup_html), min_width=400, max_width=400) Marker(location=[lat, lng], popup=popup, icon=Icon(color="red")).add_to(marker_cluster) marker_cluster.add_to(my_map) my_map.save(dest)
def build_map(trackpoint, trips): ''' Build and display Folium map ''' html_file = args.output # color map for heatmap plugin heatmap_grad = \ {0.0: '#000004', 0.1: '#160b39', 0.2: '#420a68', 0.3: '#6a176e', 0.4: '#932667', 0.5: '#bc3754', 0.6: '#dd513a', 0.7: '#f37819', 0.8: '#fca50a', 0.9: '#f6d746', 1.0: '#fcffa4'} fmap = Map(tiles='CartoDB dark_matter', prefer_canvas=True, max_zoom=16) # Individual coordonate as heatmap HeatMap( trackpoint, radius=5, blur=5, gradient=heatmap_grad, max_zoom=19).add_to(fmap) # Trace the trip as polyline for trip in trips: PolyLine( locations=trip, weight=5, color='#FFC300', opacity=0.6).add_to(fmap) # Set map bounds fmap.fit_bounds(fmap.get_bounds()) # save map to HTML file and open with browser print('writing ' + html_file + '...') fmap.save(html_file) webbrowser.open(html_file, new=2, autoraise=True) print('done')
def main(): # tokyo_geo = '../tokyoGeoJson/tokyo.json' tokyo_geo = '../JapanCityGeoJson/geojson/13/tokyo23.json' tokyo_data = pd.read_csv(addedcode_tokyo_cases) tokyo_data['Municipality_code'] = tokyo_data['Municipality_code'].astype(str) tokyo_data['Num_cases'] = tokyo_data['Num_cases'].astype(int) # print(tokyo_data[['Municipality_code', 'Num_cases']]) # m = folium.Map(location=[48, -102], zoom_start=3) # 東京都港区芝公園を設定 tokyo23_location = [35.658593, 139.745441] # m = folium.Map(location=tokyo23_location, # tiles='https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}.png', # attr='OpenStreetMap', # zoom_start=11) m = Map(location=tokyo23_location, tiles='cartodbpositron', attr='OpenStreetMap', zoom_start=11) choropleth = Choropleth( geo_data=tokyo_geo, data=tokyo_data, columns=['Municipality_code', 'Num_cases'], # key_on='feature.properties.code', key_on='feature.id', name='choropleth', fill_opacity=0.7, line_opacity=0.2, # line_color='red', fill_color='OrRd', # bins=[0, 100, 200, 300, 400, 500] # nan_fill_color="blue" ).add_to(m) print(type(choropleth.geojson)) print(type(choropleth.color_scale)) # 地図をhtml形式で出力 LayerControl().add_to(m) m.save(outfile="choropleth_map.html")
def create_map(result): row = next(result.iterrows())[1] m = Map(location=[row.latitude, row.longitude], zoom_start=13, tiles='Stamen Terrain') feature_group = FeatureGroup(name='Some icons') for index, row in result.iterrows(): x = "not planned" if str(row.openHouse) != "nan": x = datetime.datetime.strptime(row.openHouse, "%Y-%m-%dT%H:%M:%S.000z") x = x.strftime('%b %d %Y %H:%M:%S') Marker(location=[row.latitude, row.longitude], icon=DivIcon( icon_size=(150,36), icon_anchor=(7,20), html = '<strong style="text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;">'+ '<font size="4" color="'+row['color']+'">'+str(round(row['milprice'],2))+'</>' ), popup=f"<h4>{row.street}</> <br> "+ f"<h4> Size: {str(row['size'])} m<sup>2</sup> </> <br> "+ f"<h4> Rooms: {str(int(row.rooms))} </> <br> "+ f"<h4> Floor: {str(row.floor)}</> <br> "+ f"<h4> Expense: {str(row.expense)}</> <br> "+ f"<h4> Change: -{str(row.priceChangePercentTotal)}% </> <br> "+ f"<a class='btn-floating btn-large waves-effect waves-light red'"+ f"href='add/{row.guid}'>"+ "<i class='material-icons'>add</i></a> <br>"+ f"<h4> Open House: {x} </> <br> "+ f"<a href='{row.url}' target='_blank'>link</a>" )\ .add_to(feature_group) feature_group.add_to(m) LayerControl().add_to(m) m.save(map_file)