def plot_coord(self): my_map = folium.Map( location=[self.df['lat'].mean(), self.df['lon'].mean()], tiles='Stamen Toner', zoom_start=12) pbar = ProgressBar(widgets=[ 'Plotting: ', Counter(), '/{0} '.format(len(self.df) + 1), Bar(), ' ', ETA() ], maxval=len(self.df) + 1).start() for i, r in self.df.iterrows(): if r['new'] == True: fill_color = '#33cc33' else: fill_color = '#0000ff' html = '''<html> <body> {1}br/{2}ba | {3} ft2 | ${4} | <a href="http://denver.craigslist.org/apa/{0}.html", target="_blank">link</a> <br> <img src="{5}" style="width:300"> </body> </html>'''.format(r['id'], r['bed'], r['bath'], r['sqft'], r['price'], r['image']) # iframe = folium.element.IFrame(html=html, width=250, height=50) iframe = folium.element.IFrame(html=html, width=300, height=250) poppin = folium.Popup(html=iframe) folium.RegularPolygonMarker((r['lat'], r['lon']), popup=poppin, fill_color=fill_color, number_of_sides=8, radius=6).add_to(my_map) pbar.update(i + 1) pbar.finish() for i, each in enumerate(self.points): popup = '{0} - {1}'.format(i + 1, each) folium.RegularPolygonMarker(each, popup=popup, fill_color='#ff0000', number_of_sides=3, radius=6).add_to(my_map) folium.PolyLine(self.points, color="red", weight=2.5, opacity=1).add_to(my_map) my_map.save("./found.html") subprocess.Popen(['open', 'found.html']) print 'plotting done!'
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 get_arrows(locations, color='black', size=6, n_arrows=3): ''' Get a list of correctly placed and rotated arrows/markers to be plotted Parameters locations : list of lists of lat lons that represent the start and end of the line. eg [[41.1132, -96.1993],[41.3810, -95.8021]] arrow_color : default is 'blue' size : default is 6 n_arrows : number of arrows to create. default is 3 Return list of arrows/markers ''' Point = namedtuple('Point', field_names=['lat', 'lon']) # creating point from our Point named tuple p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) # getting the rotation needed for our marker. rotation = get_bearing(p1, p2) - 90 # get an evenly space list of lats and lons for our arrows arrow_lats = np.linspace(p1.lat, p2.lat, n_arrows + 2)[1:n_arrows+1] arrow_lons = np.linspace(p1.lon, p2.lon, n_arrows + 2)[1:n_arrows+1] #creating each "arrow" and appending them to our arrows list arrows = [] for points in zip(arrow_lats, arrow_lons): arrows.append(folium.RegularPolygonMarker(location=points, fill_color=color, color=color, number_of_sides=3, radius=size, rotation=rotation)) return arrows
def make_plot(short, G): lats = nx.get_node_attributes(G, 'lat') longs = nx.get_node_attributes(G, 'lng') points = [] for node in short: points.append(tuple([lats[node], longs[node]])) ave_lat = sum(p[0] for p in points) / len(points) ave_lon = sum(p[1] for p in points) / len(points) my_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=11) folium.Marker([lats[short[0]], longs[short[0]]]).add_to(my_map) folium.Marker([lats[short[-1]], longs[short[-1]]]).add_to(my_map) #fadd lines for point in points: folium.RegularPolygonMarker(point, fill_color='#132b5e', number_of_sides=10, radius=5).add_to(my_map) folium.PolyLine(points, color="black", weight=5, opacity=1).add_to(my_map) my_map.save('templates/map_final.html') return
def ruta_sat(obse, sat_da, red): """ obser=diccionario sat_da=diccionario """ mapOBJ = folium.Map(location=[(obse["latitud"]), (obse["logitud"])], zoom_start=2) m1 = folium.Marker([float(obse["latitud"]), float(obse["logitud"])], popup=(obse["nombre"])) m1.add_to(mapOBJ) k_data = (list(sat_da.keys())) for nu in range(0, len(sat_da["latitud"])): pod = folium.Popup(red + " a las " + sat_da["Tiempo"][nu]) s1 = folium.RegularPolygonMarker( [sat_da["latitud"][nu], sat_da["longitud"][nu]], radius=5, popup=pod, color='#3186cc', fill_color='#3186cc', ) mapOBJ.add_children(s1) mapOBJ.save('map.html')
def getArrows(locations, color): size = 3 n_arrows = 5 Point = namedtuple('Point', field_names=['lat', 'lon']) # creating point from Point named tuple point1 = Point(locations[0][0], locations[0][1]) point2 = Point(locations[1][0], locations[1][1]) # calculate the rotation required for the marker. #Reducing 90 to account for the orientation of marker # Get the degree of rotation angle = get_angle(point1, point2) - 90 # get the evenly space list of latitudes and longitudes for the required arrows arrow_latitude = np.linspace(point1.lat, point2.lat, n_arrows + 2)[1:n_arrows + 1] arrow_longitude = np.linspace(point1.lon, point2.lon, n_arrows + 2)[1:n_arrows + 1] final_arrows = [] #creating each "arrow" and appending them to our arrows list for points in zip(arrow_latitude, arrow_longitude): final_arrows.append( folium.RegularPolygonMarker(location=points, color=color, fill_color=color, number_of_sides=3, radius=size, rotation=angle)) return final_arrows
def __get_arrow(self, locations, color='blue', size=6, fraction=0.6): Point = namedtuple('Point', field_names=['lat', 'lon']) # creating point from our Point named tuple p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) # getting the rotation needed for our marker. # Subtracting 90 to account for the marker's orientation # of due East(get_bearing returns North) rotation = self.__get_bearing(p1, p2) - 90 arrow_lats = np.array([p1.lat + fraction * (p2.lat - p1.lat)]) arrow_lons = np.array([p1.lon + fraction * (p2.lon - p1.lon)]) arrows = [] # creating each "arrow" and appending them to our arrows list for points in zip(arrow_lats, arrow_lons): arrows.append( folium.RegularPolygonMarker(location=points, line_cap='square', line_join='miter', color='black', opacity=1, weight=0.2, fill_color=color, fill_opacity=1, number_of_sides=3, radius=size, rotation=rotation)) return arrows[0]
def create_map(df, col1): regions_geo = 'regions.geojson' df1 = df.groupby('Region').size() map_1 = folium.Map(location=[52.958, 0.7], zoom_start=7) map_1.choropleth(geo_path=regions_geo, data=df1, columns=['region_code', 'Size'], key_on='properties.region_code', fill_color='BuPu', fill_opacity=0.7, line_opacity=0.2, legend_name='No. of people from region in census') for region in df['Region'].unique().tolist(): df1 = df[df['Region'].str.contains(region)] bar = vincent.Bar(df1[col1].value_counts(), width=350, height=250) xtitle = col1 + "in: " + regions.get(region) bar.axis_titles(x=xtitle, y='') loc = coordinates.get(region) popup1 = folium.Popup(max_width=800, ).add_child( folium.Vega(bar, width=400, height=300)) folium.RegularPolygonMarker(loc, fill_color='#43d9de', radius=12, popup=popup1).add_to(map_1) return map_1
def run(): html_fpath = 'viz_mallLocations.html' # _malls = get_malls() malls = {} for mn, (lat, lon, polygon) in _malls.items(): if mn not in TARGET_MALLS: continue malls[mn] = (lat, lon, polygon) max_lon, max_lat = -1e400, -1e400 min_lon, min_lat = 1e400, 1e400 for lat, lon, _ in malls.values(): if max_lon < lon: max_lon = lon if lon < min_lon: min_lon = lon if max_lat < lat: max_lat = lat if lat < min_lat: min_lat = lat # lonC, latC = (max_lon + min_lon) / 2.0, (max_lat + min_lat) / 2.0 map_osm = folium.Map(location=[latC, lonC], zoom_start=11) for mn, (lat, lon, polygon) in malls.items(): # map_osm.add_child(folium.PolyLine(locations=polygon, weight=1.0)) folium.RegularPolygonMarker((lat, lon), popup=mn, fill_color='red', radius=10).add_to(map_osm) map_osm.save(html_fpath) # html_url = 'file://%s' % (opath.abspath(html_fpath)) webbrowser.get('safari').open_new(html_url)
def plot_map(df): c_latitude = -16.673960 c_longitude = -49.270990 c_dist = 5 #km max_avg_ticket = df.client_revenue_avg.max() le = preprocessing.LabelEncoder() le.fit(df.salesman_id.unique()) colors = d3['Category10'][len(df.salesman_id.unique())] # Build map map_nyc = folium.Map(location=[c_latitude, c_longitude], zoom_start=11, width=840, height=580, tiles='cartodbpositron') # Plot Clients for i, row in df.iterrows(): folium.CircleMarker(location=[row['client_lat'], row['client_lon']], popup="{}: {}".format(i, row.client_id), fill_color= colors[le.transform([row['salesman_id']])[0]], radius=4).add_to(map_nyc) # Plot Center Salesman df_s = df[['salesman_id','salesman_lat', 'salesman_lon']].drop_duplicates() for i, row in df_s.iterrows(): lat, long = row.salesman_lat, row.salesman_lon folium.Marker([lat, long], popup=str(i), icon=folium.Icon(color=colors[le.transform([row['salesman_id']])[0]])).add_to(map_nyc) folium.RegularPolygonMarker( [lat, long], popup=str(row.salesman_id), fill_color=colors[le.transform([row['salesman_id']])[0]], number_of_sides=4, radius=7 ).add_to(map_nyc) return map_nyc
def folium_map0(request): # map m = folium.Map([51.5, -0.25], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m) m = m._repr_html_() # access to the data from DB (light and imgs_light) lights = Light.objects.all() img_lights = ImageLight.objects.all() # light. define the current date (day and month) now = datetime.datetime.now() now_day, now_month = now.day, now.month now_hour, now_min = now.hour, now.minute context = { 'my_map': m, 'lights': lights, 'now_day': now_day, 'now_month': now_month, 'img_lights': img_lights, 'now_hour': now_hour, 'now_min': now_min } return render(request, 'folium_map0/folium_map0.html', context)
def markers_placement(db_data): dots_number = 0 for record, species in db_data: lat = record.latitude lon = record.longitude if species.scientific_name in species_colourcode.keys(): dot_colour = species_colourcode[species.scientific_name] else: print(f'{species.scientific_name} не найден в словаре.') popup_text = species.scientific_name source = record.source_id if source == 9: folium.RegularPolygonMarker(location=[lat, lon], number_of_sides=3, popup=popup_text, radius=3, color=dot_colour, fill=True, fill_color="black").add_to(my_map) elif source == 10: folium.CircleMarker(location=[lat, lon], popup=popup_text, radius=3, color=dot_colour, fill=True, fill_color="black").add_to(my_map) else: print(f'Источник данных {record.source_id} не определен.') dots_number += 1 print(dots_number) return my_map
def get_arrows(locations, color='blue', size=6, n_arrows=3): """get a list of placed and rotated arrows/markers [description] Arguments: locations {[type]} -- list of lists of lat lon that represent start and end Keyword Arguments: color {str} -- [description] (default: {'blue'}) size {number} -- [description] (default: {6}) n_arrows {number} -- number of arrows to create (default: {3}) """ Point = namedtuple('Point', field_names=['lat', 'lon']) p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) ## gettting the rotation needed, subtracting 90 to account for marker's orientation rotation = get_bearing(p1, p2) - 90 ## get evenly space list of lats and lons arrow_lats = np.linspace(p1.lat, p2.lat, n_arrows + 2)[1:n_arrows + 1] arrow_lons = np.linspace(p1.lon, p2.lon, n_arrows + 2)[1:n_arrows + 1] arrows = [] for points in zip(arrow_lats, arrow_lons): arrows.append( folium.RegularPolygonMarker(location=points, fill_color=color, number_of_sides=3, radius=size, rotation=rotation)) return arrows
def get_arrows(locations, color='blue', size=6, n_arrows=3): Point = namedtuple('Point', field_names=['lat', 'lon']) # creating point from our Point named tuple p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) # getting the rotation needed for our marker. # Subtracting 90 to account for the marker's orientation # of due East(get_bearing returns North) rotation = get_bearing(p1, p2) - 90 # get an evenly space list of lats and lons for our arrows # note that I'm discarding the first and last for aesthetics # as I'm using markers to denote the start and end arrow_lats = np.linspace(p1.lat, p2.lat, n_arrows + 2)[1:n_arrows + 1] arrow_lons = np.linspace(p1.lon, p2.lon, n_arrows + 2)[1:n_arrows + 1] arrows = [] #creating each "arrow" and appending them to our arrows list for points in zip(arrow_lats, arrow_lons): arrows.append( folium.RegularPolygonMarker(location=points, fill_color=color, number_of_sides=3, radius=size, rotation=rotation).add_to(some_map)) return arrows
def health(request): m = folium.Map([51.5, -0.25], zoom_start=10) test = folium.Html('<b>Hello world</b>', script=True) popup = folium.Popup(test, max_width=2650) folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m) m = m._repr_html_() context = {'map': m} return render(request, 'health/health.html', context)
def showmapwithfolium(request): lat_long = [35.3369, 127.7306] m = folium.Map(lat_long, zoom_start=10) popText = folium.Html('<b>Jirisan</b></br>' + str(lat_long), script=True) popup = folium.Popup(popText, max_width=2650) folium.RegularPolygonMarker(location=lat_long, popup=popup).add_to(m) m = m._repr_html_() # updated datas = {'mountain_map': m} return render(request, 'maps/showmapwithfolium.html', context=datas)
def add_sites_to_map(map_obj): for site_id in site_dict: site_lat = site_dict[site_id]['lat'] site_long = site_dict[site_id]['long'] folium.RegularPolygonMarker(location=[site_long, site_lat], popup=str(site_id), fill_color='orange', number_of_sides=6, radius=5).add_to(map_obj)
def listajax(request): with connection.cursor() as cursor: sql = "SELECT * FROM mountains" cursor.execute(sql) results = cursor.fetchall() #number of items on each page number_of_item = 10 #Paginator paginator = Paginator(results, number_of_item) #query_set for first page first_page = paginator.page(1) #range of page ex range(1, 3) page_range = paginator.page_range # folium m = folium.Map([35.95, 128.00], zoom_start=7) # 우리나라 중심 좌표 : [35.95, 128.25] for result in results: lat_long = [result['y_coord'], result['x_coord']] # print(lat_long) # m = folium.Map(lat_long, zoom_start=12, tiles='Stamen Terrain') # folium 한글깨짐 해결 방법 : 아래 명령어 실행 후 서버 재실행 # sudo pip3 install git+https://github.com/python-visualization/branca.git@master text = "<b>"+result['name']+"</b><br><i>"\ +result['title']+"</i><br>"\ +result['y_coord']+"<br>"\ +result['x_coord']+"<br>" popText = folium.Html(text, script=True) popup = folium.Popup(popText, max_width=150) folium.RegularPolygonMarker(location=lat_long, popup=popup, number_of_sides=3, rotation=30, radius=7).add_to(m) m = m._repr_html_() #updated context = { 'paginator': paginator, 'first_page': first_page, 'page_range': page_range, 'mountain_map': m } if request.method == 'POST': page_n = request.POST.get('page_n', None) #getting page number # results = list(paginator.page(page_n)) results = list(paginator.page(page_n)) return JsonResponse({"results": results}) return render(request, 'mountains/mt_map_ajax.html', context)
def dataset2(self): self.excel1.get_G_excel_data(self.y) self.excel1.get_A_excel_data(self.y) self.x1 = [] self.x1 = self.excel1.str_g.split(',') print(self.excel1.str_g.split(',')) folium.RegularPolygonMarker([self.x1[0], self.x1[1]], popup='{}'.format(self.excel1.str_a), radius=3).add_to(self.map_2) self.y += 1
def datasetresult(self): self.excel1.get_B_excel_data(self.y) self.excel1.get_C_excel_data(self.y) self.excel1.get_D_excel_data(self.y) folium.RegularPolygonMarker([self.excel1.str_b, self.excel1.str_c], radius=3, color=f(self.excel1.str_d)).add_to( self.map_2) self.y += 1
def map_show(request, **kwargs): #creation of map comes here + business logic m = fl.Map([51.5, -0.25], zoom_start=10) test = fl.Html('<b>Hello world</b>', script=True) popup = fl.Popup(test, max_width=2650) fl.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m) m = m._repr_html_() #updated context = {'map': m} return render(request, 'polls/map_page.html', context)
def plot_stops(stdf, map_f=None, max_users=10, tiles='cartodbpositron', zoom=12, hex_color=-1, opacity=0.3, popup=True): if map_f == None: # initialise map lo_la = stdf[['lng', 'lat']].values center = list(np.median(lo_la, axis=0)[::-1]) map_f = folium.Map(location=center, zoom_start=zoom, tiles=tiles) # group by user and keep only the first `max_users` nu = 0 for user, df in stdf.groupby(constants.UID): if nu >= max_users: break nu += 1 if hex_color == -1: color = get_color(hex_color) else: color = hex_color for idx, row in df.iterrows(): la = row[constants.LATITUDE] lo = row[constants.LONGITUDE] t0 = row[constants.DATETIME] t1 = row[constants.LEAVING_DATETIME] u = row[constants.UID] try: ncluster = row[constants.CLUSTER] cl = '<BR>Cluster: {}'.format(ncluster) color = get_color(ncluster) except (KeyError, NameError): cl = '' fpoly = folium.RegularPolygonMarker([la, lo], radius=12, color=color, fill_color=color, fill_opacity=opacity) if popup: popup = folium.Popup('User: {}<BR>Coord: <a href="https://www.google.co.uk/maps/place/{},{}" target="_blank">{}, {}</a><BR>Arr: {}<BR>Dep: {}{}' \ .format(u, la, lo, np.round(la, 4), np.round(lo, 4), pd.datetime.strftime(t0, '%Y/%m/%d %H:%M'), pd.datetime.strftime(t1, '%Y/%m/%d %H:%M'), cl), max_width=300) fpoly = fpoly.add_child(popup) fpoly.add_to(map_f) return map_f
def showmapwithfolium(request): lat_long = [35.3369, 127.7306] m = folium.Map(lat_long, zoom_start=10) popText = folium.Html('<b>Jirisan</b></br>' + str(lat_long), script=True) # lat_long이 리스트이기 때문에 str로 변환 popup = folium.Popup( popText, max_width=2650) # max_width는 굳이 안해줘도 되지만 써야되는 상황도 생김, 2650은 해상도를 나타냄 folium.RegularPolygonMarker(location=lat_long, popup=popup).add_to(m) m = m._repr_html_() # google colabotory에서는 이 구문을 안적어도 된다. datas = {'mountain_map': m} # data['page_obj'] 이거랑 같은 뜻 return render(request, 'maps/showmapwithfolium.html', context=datas)
def get_arrows(locations, color='blue', size=6, n_arrows=3, add_to=None): """Add arrows to a hypothetical line between the first 2 locations in the locations list. Get a list of correctly placed and rotated arrows/markers to be plotted. Args: locations : List of lists of lat lon that represent the start and end of the line. eg [[41.1132, -96.1993],[41.3810, -95.8021]] The locations is a list so that it matches the input for the folium.PolyLine. color : Whatever folium can use. Default is 'blue' size : Size of arrow. Default is 6 n_arrows : Number of arrows to create. Default is 3. add_to: map or FeatureGroup the arrows are added to. Returns: list of arrows/markers Based on: https://medium.com/@bobhaffner/folium-lines-with-arrows-25a0fe88e4e """ # TODO: generalize so that locations can be any length >=2, i.e. a PolyLine with more than 1 section. import folium from collections import namedtuple import numpy as np Point = namedtuple('Point', field_names=['lat', 'lon']) # creating point from our Point named tuple p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) # getting the rotation needed for our marker. # Subtracting 90 to account for the marker's orientation # of due East(get_bearing returns North) rotation = MapManager.get_bearing(p1, p2) - 90 # get an evenly space list of lats and lons for our arrows # note that I'm discarding the first and last for aesthetics # as I'm using markers to denote the start and end arrow_lats = np.linspace(p1.lat, p2.lat, n_arrows + 2)[1:n_arrows + 1] arrow_lons = np.linspace(p1.lon, p2.lon, n_arrows + 2)[1:n_arrows + 1] arrows = [] # creating each "arrow" and appending them to our arrows list for points in zip(arrow_lats, arrow_lons): arrows.append( folium.RegularPolygonMarker(location=points, fill_color=color, number_of_sides=3, radius=size, rotation=rotation).add_to(add_to)) return arrows
def mapAddRegularPolygonMarker(map, points, color='#0000FF', txtOfPoppup="", sizeX=200, sizeY=50): poppin = folium.Popup(html=folium.element.IFrame( html=txtOfPoppup, width=sizeX, height=sizeY)) folium.RegularPolygonMarker(points, weight=2.5, opacity=1, fill_color=color, fill_opacity=1, popup=poppin).add_to(map)
def get_image_map(frame_time, df_trips, df_flux): """Create the folium map for the given time """ # Establish a base map depicting the network of trade routes folium_map = get_beautiful_base_image_map(df_flux, True) # If the naval mode is enabled if (sgs._enable_Naval): # Extract the information about the active trips, including if the trip is a land trip or a naval one current_latitude, current_longitude, coal_type, isnaval = get_active_trips(frame_time, df_trips) # Iterate on all active trips for i in range(len(current_longitude)): # As the naval mode is enabled in this case, we extend the colour palette production_colors = sgs._production_colors*2 # Plot each naval trip as a triangle if (isnaval[i] == 1) : folium.RegularPolygonMarker(location=[current_latitude[i], current_longitude[i]], radius=2, number_of_sides = 3, color=production_colors[coal_type[i]-1], fill_color=production_colors[coal_type[i]-1]).add_to(folium_map) # Plot each land trip as a circle else: folium.CircleMarker(location=[current_latitude[i], current_longitude[i]], radius=1, color=production_colors[coal_type[i]-1], fill=True).add_to(folium_map) # If the naval mode is not enabled, this is much simpler else: # Extract the information about the active trips current_latitude, current_longitude, coal_type = get_active_trips(frame_time, df_trips) # Iterate on all active trips for i in range(len(current_longitude)): # Plot each trip as a circle folium.CircleMarker(location=[current_latitude[i], current_longitude[i]], radius=1, color=sgs._production_colors[coal_type[i]-1], fill=True).add_to(folium_map) return folium_map
def add_arrow(self, points: Track, cue_points: List[Point]): for cue_point in cue_points: # get point 50m far from here. I hope this is after turning corner. point = cue_point.get_point_by_distance(50) folium.RegularPolygonMarker( location=(point.prev.latitude, point.prev.longitude), fill=True, fill_rule="nonzero", fill_opacity=1.0, color='#0000ff', number_of_sides=3, radius=15, rotation=point.direction - 90 ).add_to(self.map)
def add_arrows(self, line:tuple, n_arrows:int = N_ARROWS, color:str = ARROWS_COLOR, fill_color:str = ARROWS_FILL_COLOR, number_of_sides:int =ARROWS_SIDES, radius:int =ARROWS_SIZE, **options) -> None: #n number of halfway arrows, (x, y) loc_arrows = zip(np.linspace(line[0][0], line[1][0], n_arrows+2)[1:n_arrows+1], np.linspace(line[0][1], line[1][1], n_arrows+2)[1:n_arrows+1]) #The rotated arrow following the direction of the origin line. rotation = self.concordant_rotation(line[0], line[1]) - 90 #We plot the triangles/arrows for loc_arrow in loc_arrows: folium.RegularPolygonMarker(location=loc_arrow, color=color, fill_color=fill_color, number_of_sides=number_of_sides, radius=radius, rotation=rotation, **options ).add_to(self.__mapp)
def _generate_volcano_layer(nums, names, elevs, lats, lons): """Generate "Volcanoes of the World" FeatureGroup layer, and return it. :param nums: list :param names: list :param elevs: list :param lats: list :param lons: list :return: pandas.FeatureGroup """ embed_url = 'https://www.openstreetmap.org/export/embed.html' height = '400' width = '600' layer_type = 'cyclemap' lat_diff = 0.088 lon_diff = 0.160 fgv = folium.FeatureGroup(name="Volcanoes of the World (via GVP)") for num, name, elev, lat, lon in zip(nums, names, elevs, lats, lons): lat = float(lat) lon = float(lon) fill_color = _generate_color_string(elevation=elev) tooltip = f'{name} ({elev}m)' bbox = f'{lon-lon_diff}%2C{lat-lat_diff}%2C{lon+lon_diff}%2C{lat+lat_diff}' detail_url = f'https://volcano.si.edu/volcano.cfm?vn={num}&vtab=GeneralInfo' popup = _generate_popup(name=name, elev=elev, detail_url=detail_url, height=height, width=width, embed_url=embed_url, bbox=bbox, layer_type=layer_type) fgv.add_child(child=folium.RegularPolygonMarker(location=[lat, lon], color='white', radius=10, weight=1, number_of_sides=3, rotation=30, fill_opacity=0.7, fill_color=fill_color, tooltip=tooltip, popup=popup)) return fgv
def get_arrows(start, end, color='blue', size=6, n_arrows=1): """ Returns arrow as a polygon Based on https://medium.com/@bobhaffner/folium-lines-with-arrows-25a0fe88e4e """ # creating start end end point p1 = (start[0], start[1]) p2 = (end[0], end[1]) # normal rotation towards rotation = get_bearing(p1, p2) - 90 # arrow created with an polygon marker arrows = [] arrows.append(folium.RegularPolygonMarker(location=p2, fill_color=color, number_of_sides=3, opacity=0.3, color=color, radius=size, rotation=rotation).add_to(stationmap)) return arrows