def __init__(self, imgur_id, caption=None, aspect=None, gallery=None, size=300): self.imgur_id = imgur_id if caption is None: caption = '' self.caption = caption self.aspect = 1/aspect self._gallery = gallery options = dict( #autoPanPadding=(200, 200), autoPan=False, className='smb-map-popup' ) size_str = '{:d}px'.format(int(size)) if gallery is None: if self.aspect > 1: width = '{:d}px'.format(int(size/self.aspect)) iframe = IFrame(html=self.html, width=width, height=size_str) else: iframe = IFrame(html=self.html, width=size_str, ratio='{:0.0%}'.format(self.aspect)) self.popup = Popup(iframe, **options) else: self.popup = Popup(self.html_gallery, **options)
def test_marker_popups(): m = Map() features.Marker([45, -180], popup='-180').add_to(m) features.Marker([45, -120], popup=Popup('-120')).add_to(m) features.RegularPolygonMarker([45, -60], popup='-60').add_to(m) features.RegularPolygonMarker([45, 0], popup=Popup('0')).add_to(m) features.CircleMarker([45, 60], popup='60').add_to(m) features.CircleMarker([45, 120], popup=Popup('120')).add_to(m) m._repr_html_()
def test_polyline_popups(): m = Map([43, -100], zoom_start=4) features.PolyLine([[40, -80], [45, -80]], popup="PolyLine").add_to(m) features.PolyLine([[40, -90], [45, -90]], popup=Popup("PolyLine")).add_to(m) features.MultiPolyLine([[[40, -110], [45, -110]]], popup="MultiPolyLine").add_to(m) features.MultiPolyLine([[[40, -120], [45, -120]]], popup=Popup("MultiPolyLine")).add_to(m) m._repr_html_()
def test_marker_popups(): m = Map() folium.Marker([45, -180], popup='-180').add_to(m) folium.Marker([45, -120], popup=Popup('-120')).add_to(m) folium.RegularPolygonMarker([45, -60], popup='-60').add_to(m) folium.RegularPolygonMarker([45, 0], popup=Popup('0')).add_to(m) folium.CircleMarker([45, 60], popup='60').add_to(m) folium.CircleMarker([45, 120], popup=Popup('120')).add_to(m) folium.CircleMarker([45, 90], popup=Popup('90'), weight=0).add_to(m) m._repr_html_() bounds = m.get_bounds() assert bounds == [[45, -180], [45, 120]], bounds
def test_polyline_popups(): m = Map([43, -100], zoom_start=4) features.PolyLine([[40, -80], [45, -80]], popup='PolyLine').add_to(m) features.PolyLine([[40, -90], [45, -90]], popup=Popup('PolyLine')).add_to(m) features.PolyLine([[[40, -110], [45, -110]]], popup='MultiPolyLine').add_to(m) features.PolyLine([[[40, -120], [45, -120]]], popup=Popup('MultiPolyLine')).add_to(m) m._repr_html_() bounds = m.get_bounds() assert bounds == [[40, -120], [45, -80]], bounds
def create_popup_and_icon(query_list, host_url): # generate icon number_of_points = len(query_list) if number_of_points < 5: icon_color = "blue" elif number_of_points < 10: icon_color = "green" elif number_of_points < 20: icon_color = "yellow" elif number_of_points < 30: icon_color = "orange" else: icon_color = "red" # generate popup sources = [row[3] for row in query_list] alter, auto, geo = ( sources.count("altertravel"), sources.count("autotravel"), sources.count("geocaching"), ) text = Html( '<img src="{}popup.png?geo={}&alter={}&auto={}" alt="popup_pie">'. format(host_url, geo, alter, auto), script=True, ) return Popup(html=text), Icon(color=icon_color, icon="info-sign")
def build_ski_marker(location, data, width=475, height=250, icon_color='#966fd6', chart_kw={}): centroid = data[['latitude', 'longitude']].iloc[0].values tooltip = 'Skiing in {:s}'.format(location) chart = build_ski_chart(location, data, width=width - 75, height=height - 25, **chart_kw) popup = Popup(max_width=width).add_child( VegaLite(chart.to_json(), width=width, height=height)) icon_kw = dict(icon_shape='circle', border_width=0, text_color='white', border_color='white', background_color='black', inner_icon_style='font-size:11px; padding-top: 1px;') icon = BeautifyIcon('line-chart', **icon_kw) marker = Marker(location=centroid, icon=icon, tooltip=tooltip, popup=popup) return marker
def __init__(self, geo: GeoPoint, popup_path: str, *args, **kwargs): self.geo = geo weather = Jinja2Processor(popup_path, casts=geo.get_weather()).content self.marker = Marker(location=[self.geo.latitude, self.geo.longitude], popup=Popup(weather), *args, **kwargs)
def plot_stops(folium_map: FoliumMap, clustered: bool = True): """ Plot all the stops onto ``folium_map``. ``clustered`` determines if the stop will be clustered/expanded upon zoom. Could use customized color in the future for better rendering effect. """ if clustered: parent = MarkerCluster().add_to(folium_map) else: parent = folium_map for stop in ctrl_stops.all_data: ridership = ctrl_ridership_stop.get_stop_data_by_id(stop.stop_id) popup = Popup(f"{stop.name}<br>Weekday ridership: {ridership.weekday if ridership else '(unavailable)'}" f"<br>Wheelchair Accessible: {stop.wheelchair_accessible}", min_width=250, max_width=800) if stop.wheelchair_accessible: icon_c = "green" else: icon_c = "lightred" Marker( stop.coordinate, popup=popup, icon=Icon(color=icon_c, icon_color="white", icon="bus", angle=0, prefix="fa") ).add_to(parent)
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 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 popup = Popup(addr) Marker([lat, lon], popup=popup).add_to(ip_map) ip_map.save('multi_map.html') except ValueError as err: print(f'[error] {err}') except geoip2.errors.AddressNotFoundError: logger.warning(f"[-] Address {addr} is not in the geoip database.") except FileNotFoundError: geolite_check()
def get_marker(self, width=450, height=250, icon_color='#966fd6', chart_kw={}): chart = self.build_chart(width=width - 75, height=height - 25, **chart_kw) popup = Popup(max_width=width).add_child( VegaLite(chart.to_json(), width=width, height=height)) icon_kw = dict(icon_shape='circle', border_width=0, text_color='white', border_color='white', background_color='green', inner_icon_style='font-size:11px; padding-top: 1px;') icon = BeautifyIcon('line-chart', **icon_kw) location = self.data.iloc[0][['latitude', 'longitude']].values marker = Marker(location=location, icon=icon, tooltip=self.semantic, popup=popup) return marker
def get_map_render(df, the_geom_col): """ get map from a dataframe and the_geom_column name. reads from map.html and renders it into the dataframe. :param df: dataframe to get data from :param the_geom_col: the column that contains the the_geom column :return: the html render that contains the plot """ # print(df.columns, the_geom_col) yyc_coordinates = (51.121191, -114.048240) yyc_map = folium.Map(location=yyc_coordinates, zoom_start=10) src_geo_df = get_geo_df(df, the_geom_col) print(df) print(src_geo_df) for index, values in enumerate(src_geo_df): # print(index, values) geojson_polygon = get_geo_json_form_df(src_geo_df, index) print(geojson_polygon) lines = [geojson_polygon.coordinates] print(lines) folium.PolyLine(lines, weight=12, color='red', popup=Popup('Max volume location')).add_to(yyc_map) return yyc_map
def add_cities(map): cities = read_csv('worldcities.csv').iloc[:, [1, 2, 3, 4, 7, 8, 9]] latitudes, longitiudes = cities['lat'], cities['lng'] name = cities['city_ascii'] country = cities['country'] admin_name = cities['admin_name'] population = cities['population'] fg_05to1m_cities = FeatureGroup(name='500k-1m', show=False) fg_1to2m_cities = FeatureGroup(name='1m-2m', show=False) fg_2to5m_cities = FeatureGroup(name='2m-5m', show=False) fg_5to10m_cities = FeatureGroup(name='5m-10m', show=False) fg_more_than_10m_cities = FeatureGroup(name='>10m', show=False) for i in range(len(cities)): if nan_to_num(population[i]) < 500000: continue html = f'City: <a href="https://www.google.com/search?q={name[i]} city" target="_blank">{name[i]}</a><br> \ Admin: {admin_name[i]}<br> \ Country: {country[i]}<br>\ Population: {population[i]}' iframe = IFrame(html=html, width=200, height=200) coords = (latitudes[i], longitiudes[i]) if population[i] < 1000000: fg_05to1m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] < 2000000: fg_1to2m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] < 5000000: fg_2to5m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] < 10000000: fg_5to10m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) elif population[i] >= 1000000: fg_more_than_10m_cities.add_child( Marker(location=coords, popup=Popup(iframe))) map.add_child(fg_05to1m_cities) map.add_child(fg_1to2m_cities) map.add_child(fg_2to5m_cities) map.add_child(fg_5to10m_cities) map.add_child(fg_more_than_10m_cities)
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 add_volcanoes(map): map = map volcanoes = read_excel('volcanoes.xlsx').iloc[1:, [1, 2, 4, 5, 6]] latitudes, longitudes = volcanoes['Latitude'], volcanoes['Longitude'] name = volcanoes['Volcano Name'] country = volcanoes['Country'] elevation = volcanoes['Elev'] fg_volcanoes = FeatureGroup(name='Volcanoes', show=False) def color_by_elevation(elev): if type(elev) == str: return 'white' if elev <= -4000: return 'darkblue' if elev <= -2000: return 'cadetblue' if elev <= 0: return 'lightblue' if elev <= 2000: return 'orange' if elev <= 4000: return 'red' if elev <= 6000: return 'darkred' else: return 'black' for i in range(len(volcanoes)): i += 1 if isnan(elevation[i]): elevation[i] = 'Unknown' if name[i] == 'Unnamed': html = f'Volcano name:{name[i]}<br>Height: {elevation[i]} m<br> {country[i]}' else: html = f'Volcano name:<b4> <a href="https://www.google.com/search?q={name[i]} volcano" target="_blank">{name[i]}</a><br> \ Height: {elevation[i]} m<br> {country[i]}' iframe = IFrame(html=html, width=200, height=100) coords = (latitudes[i], longitudes[i]) fg_volcanoes.add_child( CircleMarker(location=coords, popup=Popup(iframe), color="gry", fill_color=color_by_elevation(elevation[i]), fill_opacity=0.9, radius=6)) i -= 1 map.add_child(fg_volcanoes)
def _convert_spotted_location_to_popup(self, address, time: str): popup_msg = dumps(address, ensure_ascii=False).split('"') popup_formatted = "{}<br><br>".format(time) count = 1 while count < len(popup_msg) - 4: popup_formatted += "{}:<br>{}<br><br>".format( popup_msg[count].upper(), popup_msg[count + 2], ) count += 4 return Popup(IFrame(popup_formatted, width=200, height=280), max_width=200)
def plot_stops_given_with_color(folium_map: FoliumMap, stops: List[Tuple[MMTStopsAtCross, Optional[str]]]): """ Plot ``stops`` as markers onto ``folium_map``. The :class:`str` in the sub-element is the color to be used on the stop marker. If this is ``None``, then "blue" will be used. """ for stop, color in stops: popup = Popup(stop.cross_name, min_width=250, max_width=800) Marker( stop.coordinate, popup=popup, icon=Icon(color=color or "blue", icon_color="white", icon="bus", angle=0, prefix="fa") ).add_to(folium_map)
def get_volcanoes_feature_group() -> FeatureGroup: feature_group = FeatureGroup(name="Volcanoes") data = pandas.read_csv("./Volcanoes_USA.txt") latitudes = list(data['LAT']) longitudes = list(data['LON']) elevation = list(data['ELEV']) for lat, lon, elev in zip(latitudes, longitudes, elevation): feature_group.add_child( CircleMarker(location=(lat, lon), color='grey', weight=1, radius=6, popup=Popup(str(elev) + "m", parse_html=True), fill_color=get_elevation_color(elev))) return feature_group
def create_popups_from_template( location, html_template=POPUP_TEMPLATE, *args, **kwargs ): iframe = IFrame( html=html_template(*args, **kwargs), width=400, height=200 ) popup = Popup( iframe, max_width=500 ) return popup
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'] popup = Popup(QRY) Marker([lat, lon], popup=popup).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_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)
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 photos_to_map(self, image_name, coordinate): """ Parameters ---------- image_name -- image name coordinate -- coordinate tuple Returns ------- Adds markers to self.map Clicking on the markers displays popup containing image of detected traffic sign """ image = Image.open(image_name) image = image.resize((380, 270), Image.ANTIALIAS) image.save(image_name, quality=100) encoded = base64.b64encode(open(image_name, 'rb').read()) html = '<img src="data:image/png;base64,{}">'.format iframe = IFrame(html(encoded.decode('UTF-8')), width=380, height=270) popup = Popup(iframe, max_width=500) icon = Icon(color='red', icon='ok') Marker(location=[coordinate[0], coordinate[1]], popup=popup, icon=icon).add_to(self.map)
def readJobFile(): start_loc = getlnglat('北京')['result']['location'] m = Map(location=[start_loc['lat'], start_loc['lng']], zoom_start=8) path = r'C:\Users\IBM_ADMIN\AppData\Local\Programs\Python\Python35\mydata\testjob' loc_file_list = os.listdir(path) for job_file in loc_file_list: if job_file.startswith(u'北京') or 1 == 1: job_file = os.path.join(path, job_file) with open(job_file, 'r') as f: for line in f: jobinfo = {}.fromkeys( ('company', 'position', 'location', 'salary')) lineinfo = line.split('|') jobinfo['company'] = lineinfo[0] jobinfo['position'] = lineinfo[1] jobinfo['address'] = lineinfo[2] jobinfo['salary'] = lineinfo[3] try: loc = getlnglat( jobinfo['company'])['result']['location'] maker = Marker(location=[loc['lat'],loc['lng']], popup=Popup('%s\n%s\n%s' % \ (jobinfo['company'], jobinfo['position'], jobinfo['salary']) ), icon=Icon()) m.add_child(maker) except: info = sys.exc_info() print(info[0], ':', info[1]) print(jobinfo['company']) pass m.save('51job.html')
def plot_point(self, lat, lng, desc=None, clr='blue'): """ Create a single popup located at the passed coordinates. :param lat: :type lat: int or float. :param lng: :type lng: int or float. :param desc: description of the popup. :type desc: str. :param clr: :type clr: str. :return: :rtype: folium.Marker. """ if not desc: desc = str((lat, lng)) return Marker(location=(lat, lng), popup=Popup(desc, parse_html=True), icon=Icon(prefix='fa', color=clr, icon='circle', icon_color='white'))
def user_info(user_id=None): """ Get information for specific user, delete user, mark location on the map """ sql = ''' SELECT * FROM users_table where id = %s''' conn = db.connect() res = conn.execute(sql, (user_id, )) user = res.first() conn.close() center = [-0.023559, 37.9061928] user_map = folium.Map(location=center, zoom_start=2) location = [user['latitude'], user['longitude']] folium.Marker(location, popup=Popup('Random user location ', show=True)).add_to(user_map) if request.method == 'POST': sql = ''' Delete FROM users_table where id = %s''' db.execute(sql, (user_id, )) return redirect('/') return render_template('user.html', user=user, user_id=user_id, user_map=user_map._repr_html_())
def show_map(coords: list, web_engine_view: QWebEngineView, pop_up: str = None, university=None, kindergarden=None, schools=None, highschools=None, transport=None, charging=None, bicycle=None, groceries=None, services=None, sports=None): icon_size = (45, 45) small_icon = (40, 40) max_width = 400 bytes_io = BytesIO() map_builder = Map(location=coords, tiles="CartoDB positron", zoom_start=16) map_icon = CustomIcon(up(up(__file__)) + "/images/marker.png", icon_size=icon_size) if kindergarden: kindergarden_cluster = MarkerCluster( name='barnehage', show=False).add_to(map_builder) for pois in kindergarden: pois_icon = CustomIcon(up(up(__file__)) + "/images/kindergarden.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(kindergarden_cluster) if schools: schools_cluster = MarkerCluster(name="barneskole", show=False).add_to(map_builder) for pois in schools: pois_icon = CustomIcon(up(up(__file__)) + "/images/schools.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(schools_cluster) if highschools: highschools_cluster = MarkerCluster(name='vidregåendeskole', show=False).add_to(map_builder) for pois in highschools: pois_icon = CustomIcon(up(up(__file__)) + "/images/highschools.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(highschools_cluster) if university: university_cluster = MarkerCluster(name='hogskole_universitet', show=False).add_to(map_builder) for pois in university: pois_icon = CustomIcon(up(up(__file__)) + "/images/university.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(university_cluster) if transport: transport_cluster = MarkerCluster(name='holdeplass', show=False).add_to(map_builder) for pois in transport: pois_icon = CustomIcon(up(up(__file__)) + "/images/transport.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(transport_cluster) if charging: charging_cluster = MarkerCluster(name='ladeplass', show=False).add_to(map_builder) for pois in charging: pois_icon = CustomIcon(up(up(__file__)) + "/images/charging.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(charging_cluster) if bicycle: bicyle_cluster = MarkerCluster(name='bysykler', show=False).add_to(map_builder) for pois in bicycle: pois_icon = CustomIcon(up(up(__file__)) + "/images/bicycle.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(bicyle_cluster) shops_cluster = MarkerCluster(name="butikker", show=False).add_to(map_builder) if groceries: for pois in groceries: pois_icon = CustomIcon(up(up(__file__)) + "/images/groceries.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(shops_cluster) if services: for pois in services: pois_icon = CustomIcon(up(up(__file__)) + "/images/services.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(shops_cluster) if sports: sports_cluster = MarkerCluster(name='sportsaktiviteter', show=False).add_to(map_builder) for pois in sports: pois_icon = CustomIcon(up(up(__file__)) + "/images/sports.png", icon_size=small_icon) lat = pois["Breddegrad"] long = pois["Lengdegrad"] pois_pop_up = Popup(CreateHtmlTable(pois).html_table(), max_width=max_width) Marker(location=[lat, long], icon=pois_icon, popup=pois_pop_up).add_to(sports_cluster) if pop_up: Marker(coords, icon=map_icon, popup=Popup(pop_up, max_width=max_width)).add_to(map_builder) else: Marker(coords, icon=map_icon).add_to(map_builder) TileLayer('CartoDB dark_matter').add_to(map_builder) TileLayer('OpenStreetMap').add_to(map_builder) TileLayer( 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', attr= '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' 'contributors, Tiles style by <a href="https://www.hotosm.org/" ' 'target="_blank">Humanitarian OpenStreetMap Team</a> hosted by ' '<a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap ' 'France</a>', name='openstreetmap_hot').add_to(map_builder) TileLayer('Stamen Toner').add_to(map_builder) TileLayer( 'https://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='esri_worldimagery').add_to(map_builder) TileLayer( 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/' 'tile/{z}/{y}/{x}', attr='Tiles © Esri — Source: Esri, DeLorme, ' 'NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, ' 'Esri China (Hong Kong), Esri (Thailand), TomTom, 2012', name='esri_worldstreetmap').add_to(map_builder) TileLayer( 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/' 'tile/{z}/{y}/{x}', attr='Tiles © Esri — Esri, DeLorme, NAVTEQ, ' 'TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, ' 'Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri ' 'China (Hong Kong), and the GIS User Community', name='esri_worldtopomap').add_to(map_builder) TileLayer( 'https://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png', attr='Map <a href="https://memomaps.de/">memomaps.de</a> ' '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' 'map data © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors', name='openvkarte').add_to(map_builder) TileLayer( 'https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png', attr= '<a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases" ' 'title="CyclOSM - Open Bicycle render">CyclOSM</a> | Map data: © ' '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' 'contributors', name='cyclosm').add_to(map_builder) TileLayer( 'http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png', attr= '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> ' 'contributors & USGS', name='mtbmap').add_to(map_builder) railway_feature = FeatureGroup('jernbane_tbane', show=False) TileLayer( 'https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright' '">OpenStreetMap</a> contributors | Map style: © <a href=' '"https://www.OpenRailwayMap.org">OpenRailwayMap</a> (<a href=' '"https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='openrailwaymap').add_to(railway_feature) railway_feature.add_to(map_builder) safecast_feature = FeatureGroup('miljø', show=False) TileLayer( 'https://s3.amazonaws.com/te512.safecast.org/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://blog.safecast.org/about/">SafeCast</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='safecast').add_to(safecast_feature) safecast_feature.add_to(map_builder) trails_feature = FeatureGroup('turstil', show=False) TileLayer( 'https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='waymarkedtrails_hiking').add_to(trails_feature) trails_feature.add_to(map_builder) cycling_feature = FeatureGroup('sykkelsti', show=False) TileLayer( 'https://tile.waymarkedtrails.org/cycling/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='waymarkedtrails_cycling').add_to(cycling_feature) cycling_feature.add_to(map_builder) slopes_feature = FeatureGroup('bakker_helning', show=False) TileLayer( 'https://tile.waymarkedtrails.org/slopes/{z}/{x}/{y}.png', attr= 'Map data: © <a href="https://www.openstreetmap.org/copyright">' 'OpenStreetMap</a> contributors | Map style: © ' '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> ' '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)', name='waymarkedtrails_slopes').add_to(slopes_feature) slopes_feature.add_to(map_builder) LayerControl().add_to(map_builder) map_builder.save(bytes_io, close_file=False) web_engine_view.setHtml(bytes_io.getvalue().decode()) web_engine_view.show()
<td title="Website or other link to this market’s online presence."><a href="' + (i[17][0] if i[17] != None else "google.com") + '">' + (str(i[17][0]) if i[17] != None else "None") + '</a></td>\ </tr>\ <tr>\ <td>Operating Hours</td>\ <td title="Day and Hours the market is open.">' + str(i[18]) + '</td>\ </tr>\ <tr>\ <td>Operating Season</td>\ <td title="Month and day when the market opens and closes for the year.">' + str(i[19]) + '</td>\ </tr>\ </table>', script=True) desc = Popup(test, parse_html=True, max_width=450) random_number = random.randint(1118481, 16777215) hex_number = str(hex(random_number)) hex_number = '#' + hex_number[2:] marker = folium.CircleMarker(location=[i[25], i[26]], radius=7, tooltip=i[10], popup=desc, color=hex_number, fill_color='#c4761c') marker.add_to(folium_map) folium_map.save("FarmersMarketNYS.html")
t = time.time() location_dict = create_location_dict(posts_object) print("Done in: ", time.time() - t) # Create map object my_map = Map(location=[50.3005988, 24.2444963], zoom_start=4) # put the data from Instagram profile on the map for location in location_dict: try: html = '<head><style> div{display: block; text-align: center;} </style></head>' for post_tuple in location_dict[location]: date = post_tuple[0].date() url = post_tuple[1] post_url = 'http://www.instagram.com/p/' + post_tuple[3] likes = post_tuple[2] html += f""" <div><strong>{date}</strong><br> <a href="{post_url}" target='popup'><img src="{url}" width=150></a><br> {likes} 👍<br><br></div> """ # Creating IFrame object. It allows us to render html code for popup elements instead of using # default popup's design iframe = branca.element.IFrame(html=html, width=180, height='100%') popup = Popup(iframe) Marker(location, popup=popup).add_to(my_map) except ValueError: continue my_map.save('map.html')