def visualize_map(self, df, theme=None): dark_attr = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png" positron_attr = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png" osm_attr = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" if theme == 'dark': map = Map(location=[34.0522, -118.2437], control_scale=True, zoom_start=12, attr=dark_attr, tiles="cartodbdark_matter") elif theme == 'positron': map = Map(location=[34.0522, -118.2437], control_scale=True, zoom_start=12, attr=positron_attr, tiles="cartodbpositron") else: map = Map(location=[34.0522, -118.2437], control_scale=True, zoom_start=12, attr=osm_attr, tiles="openstreetmap") cluster = MarkerCluster().add_to(map) locations = df[['latitudes', 'longitudes']].values.tolist() for point in range(len(locations)): Marker(locations[point], popup=df['listing_name'][point]).add_to(cluster) return map
def initialize_canvass(self, center=None) -> None: """ determine the center based on a given locations by finding the latitude mean and longitude mean """ if self.canvass is None: if center is None: self.canvass = Map(location=self.center, zoom_start=6) else: self.canvass = Map(location=center, zoom_start=6)
def build_heat_map(data, sample): heat_map = Map(**MAP_DEFAULT_START_PARAMS) HeatMap(data[['lat', 'long']], radius=10).add_to(heat_map) if 'lat' in sample.columns: heat_map.add_child( Circle(*sample[['lat', 'long']].values, radius=1.1e5)) return heat_map
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 __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 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 create_map(data): if not data: raise PreventUpdate df = pd.DataFrame(data) qtd_sem_latlon = df[["address_lat", "address_lon"]].isna().max(axis=1).sum() df = df.dropna(subset=["address_lat", "address_lon"]) map = Map( location=df[["address_lat", "address_lon"]].mean().values, height="89%", tiles= "https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", attr="toner-bcg", ) marker_cluster = MarkerCluster().add_to(map) for _, row in df.iterrows(): Marker( location=[row["address_lat"], row["address_lon"]], popup=box(**row), ).add_to(marker_cluster) return f"{qtd_sem_latlon} imóveis sem latitude ou longitude", map._repr_html_( )
def getMap(): # initialize the map to the starting location and add starting location # this library will base location off user IP address. It works locally, but # not once the app is deployed (different IP address) g = geocoder.ip('me') start_coords = g.latlng themap = Map(location=start_coords, tiles="OpenStreetMap", zoom_start=15) folium.Marker(location=start_coords, popup='Your Location', icon=folium.Icon(color='red', icon='hi')).add_to(themap) # get nearby restaurant data startloc = str(start_coords[0]) + "," + str(start_coords[1]) df = getRestaurantData(startloc) data = cleanDataframe(df) # add restaurants to the map for (y, x) in data.iterrows(): loc = [] loc.append(x['latitude']) loc.append(x['longitude']) color = "green" if (x['rating'] < 4.0): color = "orange" popup_text = "{}<br> Cuisine: {}<br> Average Rating: {}<br> Number of Reviews: {}" popup_text = popup_text.format(x["name"], x["descriptors"], x["rating"], x['review_count']) themap.add_child( Marker(location=loc, popup=popup_text, icon=folium.Icon(color=color))) return themap._repr_html_()
def map_it(df, lattitude, longitude): map_city = Map(location=[lattitude, longitude], zoom_start=15) for i, row in df.iterrows(): name = {"location": [row["lat"], row["long"]], "tooltip": row["name"]} if row["category"] == "Starbucks": icon = Icon(color="black", prefix="fa", icon="coffee", icon_color="white") elif row["category"] == "Preschool": icon = Icon(color="red", prefix="fa", icon="child", icon_color="white") elif row["category"] == "Vegan_Restaurant": icon = Icon(color="green", prefix="fa", icon="leaf", icon_color="white") else: icon = Icon(color="lightblue", prefix="fa", icon="futbol-o", icon_color="black") Marker(**name, icon=icon).add_to(map_city) return map_city
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()
def as_map(self, img_name=None): if img_name == None: coord_index = self.meta_keys.index('GPS') coord_list = [ self.metadata[key][coord_index][0:2] + [key] for key in self.metadata.keys() ] print(coord_list) cood_t = list(map(list, zip(*coord_list))) center = [(max(cood_t[0]) + min(cood_t[0])) / 2, (max(cood_t[1]) + min(cood_t[1])) / 2] print(center) print(coord_list) img_map = Map( location=center, zoom_start=13, width='100%', height='100%', tiles='https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', attr='Google') for x, y, img in coord_list: Marker(location=[x, y], popup='', tooltip=img).add_to(img_map) return (img_map._repr_html_()) return ('')
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 map_points(df, lat_col='latitude', lon_col='longitude', zoom_start=11, plot_points=False, pt_radius=15, draw_heatmap=False, heat_map_weights_col=None, heat_map_weights_normalize=True, heat_map_radius=15): """Creates a map given a dataframe of points. Can also produce a heatmap overlay Arguments: df: dataframe containing points to maps lat_col: Column containing latitude (string) lon_col: Column containing longitude (string) zoom_start: Integer representing the initial zoom of the map plot_points: Add points to map (boolean) pt_radius: Size of each point draw_heatmap: Add heatmap to map (boolean) heat_map_weights_col: Column containing heatmap weights heat_map_weights_normalize: Normalize heatmap weights (boolean) heat_map_radius: Size of heatmap point Returns: folium map object """ # center map in the middle of points middle_lat = df[lat_col].mean() + 0.2 middle_lon = df[lon_col].mean() curr_map = Map(location=[middle_lat, middle_lon], tiles='Cartodb Positron', zoom_start=zoom_start) # add points to map if plot_points: for _, row in df.iterrows(): if row['station_type'] == 'aq': Marker([row[lat_col], row[lon_col]], popup=row['station'], icon=folium.Icon(color='green')).add_to(curr_map) else : Marker([row[lat_col], row[lon_col]], popup=row['station'], icon=folium.Icon(color='blue')).add_to(curr_map) # add heatmap if draw_heatmap: # convert to (n, 2) or (n, 3) matrix format if heat_map_weights_col is None: # cols_to_pull = [lat_col, lon_col] heat_df = [[row[lat_col], row[lon_col]] for index, row in df.iterrows()] else: # if we have to normalize if heat_map_weights_normalize: df[heat_map_weights_col] = \ df[heat_map_weights_col] / df[heat_map_weights_col].sum() heat_df = [[row[lat_col], row[lon_col], row[heat_map_weights_col]] for index, row in df.iterrows()] HeatMap(heat_df).add_to(curr_map) return curr_map
def heatmap(gdf, location, gradient=None): """ This is a function that creates a heatmap. Parameters ---------- gdf (geodata frame) : GeoDataFrame location (list): latitude and longitude of central map location (e.g. NYC = [40.693943, -74.025]) gradient (dict) (default:None): option to change the gradient, useful when combining other heatmaps Returns ------- a heatmap of where a specific class of data is _ by sensor """ emptymap = Map(location=location, zoom_start=12) # create heatmap hm = HeatMap( list(zip(gdf.latitude.values, gdf.longitude.values)), min_opacity=0.2, radius=10, blur=13, gradient=gradient, max_zoom=1, ) # add heatmap layer to empty layer emptymap.add_child(hm) return emptymap
def play(loc_id=None): # TODO: # - hook this up to a DB model # - randomize ordering (or create sets??) # - track session/user to prevent duplicates if not loc_id: loc_id = random.choice(range(len(LOCATIONS))) return redirect(url_for("play", loc_id=loc_id)) try: loc_id = int(loc_id) except ValueError: abort(400) place_data = LOCATIONS[int(loc_id)] place_name = place_data.name hints = [ ("Hemisphere (latitude)", place_data.hemisphere_lat), ("Hemisphere (longitude)", place_data.hemisphere_lon), ("Continent (ocean for islands)", place_data.continent_or_ocean), ("Country", place_data.country_name), ] next_loc_id = loc_id + 1 if loc_id < len(LOCATIONS) else 0 map = Map(location=place_data.coordinates, **DEFAULT_MAP_KWARGS )._repr_html_() # TODO override to e.g. change placeholder etc return render_template( "play.html", map=map, loc_id=loc_id, next_loc_id=next_loc_id, place_name=place_name, hints=hints, )
def mapsites(df, col=None): """Maps site measurements and labels them by site name and date. If a numeric column name is optionally entered then the icons will be color coded according to value quartile, with green as the lowest quartile up to dark red as the top quartile.""" m = Map(location=[41.76, -83.26]) if col: crange = df[col].describe() for i in df.index: lat = df.loc[i, 'Latitude (decimal deg)'] long = df.loc[i, 'Longitude (decimal deg)'] site = df.loc[i,'Site'] date = df.loc[i, 'Date'] if col: val = df.loc[i, col] if val <= crange['25%']: color = 'green' elif val <= crange['50%']: color = 'orange' elif val <= crange['75%']: color = 'red' else: color = 'darkred' Marker([lat, long], popup=(lat,long), tooltip=(site, date), icon=Icon(color=color)).add_to(m) else: Marker([lat, long], popup=(lat,long), tooltip=(site, date)).add_to(m) return m
def map_api_call(): url = "https://api.odcloud.kr/api/15077586/v1/centers?page=1&perPage=300&serviceKey=" + get_apikey( "serviceKey", "secret.json") result = requests.get(url=url) json_result = json.loads(str(result.text)) m = Map(location=[36.5053542, 127.7043419], zoom_start=8) marker_cluster = MarkerCluster().add_to(m) for idx in range(json_result["currentCount"]): address = json_result["data"][idx]["address"] centerName = json_result["data"][idx]["centerName"] facilityName = json_result["data"][idx]["facilityName"] lat = json_result["data"][idx]["lat"] lng = json_result["data"][idx]["lng"] iframe = centerName + ": <br> " + facilityName + ":<br> " + address popup = folium.Popup(iframe, min_width=200, max_width=200) Marker(location=[lat, lng], popup=popup, tooltip=centerName + " : " + facilityName, icon=Icon(color='green', icon='flag')).add_to(marker_cluster) account_info = get_apikey("Account", "secret.json") return render_template(template_name_or_list="index.html", map=m._repr_html_(), account_info=account_info)
def create_map(self): try: from folium import Map from folium.vector_layers import Polygon import branca.colormap as cm except ImportError: # pragma: no cover logger.error('Mapping requires folium==0.10.0 to be installed, geo mapping will not work.' 'Install it with: pip install scikit-hts[geo]') return _map = Map(tiles="cartodbpositron") geos = self.get_geos() max_lat, max_lon, min_lat, min_lon = get_min_max_ll(geos) geos = [(i, numpy.log(j + 1) / (self.tree.get_node_height(k) + 1), k) for i, j, k in geos] mx, mn = max([j for i, j, k in geos]), min([j for i, j, k in geos]) geos = [(i, (j - mn) / (mx - mn), k) for i, j, k in geos] for points, count, h in sorted(geos, key=lambda x: x[1]): tooltip = f"hex: {h}" polygon = Polygon(locations=points, tooltip=tooltip, fill=True, color=cm.linear.OrRd_03.rgb_hex_str(count), fill_color=cm.linear.OrRd_03.rgb_hex_str(count), fill_opacity=0.3, weight=3, opacity=0.4) polygon.add_to(_map) _map.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]]) return _map
def create_map(self): _map = Map(tiles="cartodbpositron") geos = self.get_geos() max_lat, max_lon, min_lat, min_lon = get_min_max_ll(geos) geos = [(i, numpy.log(j + 1) / (self.tree.get_node_height(k) + 1), k) for i, j, k in geos] mx, mn = max([j for i, j, k in geos]), min([j for i, j, k in geos]) geos = [(i, (j - mn) / (mx - mn), k) for i, j, k in geos] for points, count, h in sorted(geos, key=lambda x: x[1]): tooltip = f"hex: {h}" polygon = Polygon(locations=points, tooltip=tooltip, fill=True, color=cm.linear.OrRd_03.rgb_hex_str(count), fill_color=cm.linear.OrRd_03.rgb_hex_str(count), fill_opacity=0.3, weight=3, opacity=0.4) polygon.add_to(_map) _map.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]]) return _map
def draw_map_once_function_call(): # df = pd.read_csv("vac.csv") # df = pd.read_csv("vac210315.csv") # df = pd.read_csv("csv/vac210331.csv") df = pd.read_csv("csv/test.csv") m = Map(location=[36.5053542, 127.7043419], zoom_start=8) marker_cluster = MarkerCluster().add_to(m) addr_list = [] for idx in range(len(df)): addr_list.append(df.loc[idx, "address"]) # but one call func not multiple call # lon_list, lat_list = getLatLng_list(addr_list) for idx, addr in enumerate(addr_list): location_name = df.loc[idx, "location_name"] telephone = df.loc[idx, "telephone"] print(telephone) latitude = df.loc[idx, "latitude"] longitude = df.loc[idx, "longitude"] iframe = location_name + ":<br> " + addr + ": <br> " + telephone print(idx, ": ", iframe) popup = folium.Popup(iframe, min_width=200, max_width=200) Marker(location=[latitude, longitude], popup=popup, tooltip=location_name, icon=Icon(color='green', icon='flag')).add_to(marker_cluster) account_info = get_apikey("Account", "secret.json") return render_template(template_name_or_list="index.html", map=m._repr_html_(), account_info=account_info)
def test_rectangle(): m = Map() location = [[45.6, -122.8], [45.61, -122.7]] rectangle = Rectangle( bounds=location, popup='I am a rectangle', color='black', weight=2, fill_opacity=0.6, opacity=1, fill=True, ) rectangle.add_to(m) expected_options = { 'bubblingMouseEvents': True, 'color': 'black', 'dashArray': None, 'dashOffset': None, 'fill': True, 'fillColor': 'black', 'fillOpacity': 0.6, 'fillRule': 'evenodd', 'lineCap': 'round', 'lineJoin': 'round', 'opacity': 1, 'stroke': True, 'weight': 2, } m._repr_html_() expected_rendered = """ var {name} = L.rectangle( {location}, {{ "bubblingMouseEvents": true, "color": "black", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "black", "fillOpacity": 0.6, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "opacity": 1, "stroke": true, "weight": 2 }} ) .addTo({map}); """.format(name=rectangle.get_name(), location=location, map=m.get_name()) rendered = rectangle._template.module.script(rectangle) assert rendered.strip().split() == expected_rendered.strip().split() assert rectangle.get_bounds() == location assert json.dumps(rectangle.to_dict()) == rectangle.to_json() assert rectangle.options == json.dumps(expected_options, sort_keys=True, indent=2) # noqa
def bicycling(origin, destination, alternative="bicycling"): """ Recoge las cordenadas y dibuja el mapa con direcciones (en bici) """ coordenadas = waypoints(origin=origin, destination=destination, alternative="bicycling") stopsdest = db.bicimad.find({ "coordinates": { "$geoWithin": { "$centerSphere": [[coordenadas[2]["lng"], coordenadas[2]["lat"]], 0.00007885743614075527] } } }).limit(1) stopsorig = db.bicimad.find({ "coordinates": { "$geoWithin": { "$centerSphere": [[coordenadas[1]["lng"], coordenadas[1]["lat"]], 0.00007885743614075527] } } }).limit(1) wpsneardest = [] wpsnearorig = [] for i in stopsdest: wpsneardest.append(i) for i in stopsorig: wpsnearorig.append(i) wpsneardest = wpsneardest[0]["coordinates"] wpsnearorig = wpsnearorig[0]["coordinates"] mapa = Map(location=[coordenadas[2]["lat"], coordenadas[2]["lng"]], zoom_start=14) chincheta2 = Marker( location=[coordenadas[1]["lat"], coordenadas[1]["lng"]], tooltip="origen", popup="o") chinchetad = Marker( location=[coordenadas[2]["lat"], coordenadas[2]["lng"]], tooltip="destino", popup="d") bicimador = Marker(location=[wpsnearorig[1], wpsnearorig[0]], tooltip="orbici", popup="bo", icon=Icon(icon='heart', color='#f7b5f5')) bicimaddest = Marker(location=[wpsneardest[1], wpsneardest[0]], tooltip="destbici", popup="bd", icon=Icon(icon="heart", color="#f7b5f5")) chincheta2.add_to(mapa) chinchetad.add_to(mapa) bicimador.add_to(mapa) bicimaddest.add_to(mapa) PolyLine(coordenadas[3], color="red", weight=2.5, opacity=1).add_to(mapa) return mapa
def test_mulyipolyline(): m = Map() locations = [[[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]]] multipolyline = PolyLine(locations=locations, popup='MultiPolyLine') multipolyline.add_to(m) expected_options = { 'smoothFactor': 1.0, 'noClip': False, 'bubblingMouseEvents': True, 'color': '#3388ff', 'dashArray': None, 'dashOffset': None, 'fill': False, 'fillColor': '#3388ff', 'fillOpacity': 0.2, 'fillRule': 'evenodd', 'lineCap': 'round', 'lineJoin': 'round', 'opacity': 1.0, 'stroke': True, 'weight': 3, } m._repr_html_() expected_rendered = """ var {name} = L.polyline( {locations}, {{ "bubblingMouseEvents": true, "color": "#3388ff", "dashArray": null, "dashOffset": null, "fill": false, "fillColor": "#3388ff", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 3 }} ) .addTo({map}); """.format(locations=locations, name=multipolyline.get_name(), map=m.get_name()) rendered = multipolyline._template.module.script(multipolyline) assert normalize(rendered) == normalize(expected_rendered) assert multipolyline.get_bounds() == get_bounds(locations) assert json.dumps(multipolyline.to_dict()) == multipolyline.to_json() assert multipolyline.options == expected_options
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 create_map(center=PR_CENTER, zoom=13, *args, **kwargs): m1 = Map( location=center, zoom_start=zoom, *args, **kwargs ) return m1
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 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 test_polygon_marker(): m = Map() locations = [[35.6636, 139.7634], [35.6629, 139.7664], [35.6663, 139.7706], [35.6725, 139.7632], [35.6728, 139.7627], [35.6720, 139.7606], [35.6682, 139.7588], [35.6663, 139.7627]] polygon = Polygon(locations=locations, popup='I am a polygon') polygon.add_to(m) expected_options = { 'bubblingMouseEvents': True, 'color': '#3388ff', 'dashArray': None, 'dashOffset': None, 'fill': False, 'fillColor': '#3388ff', 'fillOpacity': 0.2, 'fillRule': 'evenodd', 'lineCap': 'round', 'lineJoin': 'round', 'noClip': False, 'opacity': 1.0, 'smoothFactor': 1.0, 'stroke': True, 'weight': 3, } m._repr_html_() expected_rendered = """ var {name} = L.polygon( {locations}, {{ "bubblingMouseEvents": true, "color": "#3388ff", "dashArray": null, "dashOffset": null, "fill": false, "fillColor": "#3388ff", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 3 }} ) .addTo({map}); """.format(locations=locations, name=polygon.get_name(), map=m.get_name()) rendered = polygon._template.module.script(polygon) assert _normalize(rendered) == _normalize(expected_rendered) assert polygon.get_bounds() == get_bounds(locations) assert json.dumps(polygon.to_dict()) == polygon.to_json() assert polygon.options == json.dumps(expected_options, sort_keys=True, indent=2) # noqa
def map_city(city): """ Creates a map of the city Args: city (point): the coordinates of the city to be plotted Returns: The map of the city """ return Map(location=city['coordinates'], zoom_start=15)