def plot_path(trip, name): loc = trip.days[0].items[0].coordinate m = folium.Map(location=[loc['lat'], loc['lon']]) path = [] for i, day in enumerate(trip.days): path.extend(day.items) for j, item in enumerate(day.items): folium.Marker( location=[item.coordinate['lat'], item.coordinate['lon']], icon=folium.Icon(color=colors[i if i < len(colors) else 0]), tooltip=f'Day:{i+1},Place:{j+1}, {item.item_type}, {item.name}' ).add_to(m) folium.PolyLine( locations=[[item.coordinate['lat'], item.coordinate['lon']] for item in path], weight=5).add_to(m) m.save(name) print('saved')
def map_marker(final_course): map_line = [] map_course = folium.Map(location=[37.545905, 127.016015], zoom_start=12) cnt = 1 for i in final_course: print(i, course_default[i][0]) map_line.append([course_default[i][1], course_default[i][2]]) my_location = [course_default[i][1], course_default[i][2]] if course_default[i][0] == '현재위치': icon = 'user' elif course_default[i][0] == '마지막위치': icon = 'bed' else: icon = 'chevron-circle-down' folium.Marker(my_location, icon = plugins.BeautifyIcon(icon = icon, border_color='red', text_color='red'\ ,icon_shape = 'marker', border_width = 2),tooltip = str(cnt) + course_default[i][0]).add_to(map_course) cnt += 1 folium.PolyLine(locations=map_line, color='red', weight=4, line_opacity=1).add_to(map_course) htmlfilename = 'map_marker_test2.html' map_course.save(htmlfilename) htmltopng(htmlfilename)
def plot_route(self, lat_org, lng_org, lat_dst, lng_dst): params = {} params["key"] = self.__keyid params["origin"] = str(lat_org) + "," + str(lng_org) params["destination"] = str(lat_dst) + "," + str(lng_dst) params["mode"] = "walking" response = requests.get(self.__url, params).json() if (not response["status"] == "OK"): self.err_message = response["status"] return False decode = googlemaps.convert.decode_polyline locs_polyline = [] for step in response["routes"][0]["legs"][0]["steps"]: locs = decode(step['polyline']['points']) locs = [[loc['lat'], loc['lng']] for loc in locs] locs_polyline.extend(locs) folium.PolyLine(locs_polyline).add_to(self.map) return True
def make_html(self, directions): points = [] start_id = directions[0].id end_id = directions[len(directions) - 1].id for root in directions: points.append(tuple([float(root.lat), float(root.lon)])) endId = root.id root_map = folium.Map(location=[directions[0].lat, directions[0].lon], zoom_start=17) #add a markers for each in points: folium.Marker(each).add_to(root_map) #fadd lines folium.PolyLine(points, color="red", weight=1.5, opacity=1).add_to(root_map) file_name = start_id + ' to ' + end_id + '.html' root_map.save('./rootMap/' + file_name)
def draw_gps(user_id, locations, output_path, startTime, endTime): """ 绘制gps轨迹图 :param locations: list, 需要绘制轨迹的经纬度信息,格式为[[lat1, lon1], [lat2, lon2], ...] :param output_path: str, 轨迹图保存路径 :param file_name: str, 轨迹图保存文件名 :return: None """ m = folium.Map( bd09_to_gcj02(112.950221, 28.180776), zoom_start=16, tiles= 'http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', attr='AutoNavi') folium.PolyLine( # polyline方法为将坐标用线段形式连接起来 locations, # 将坐标点连接起来 weight=3, # 线的大小为3 color='orange', # 线的颜色为橙色 opacity=0.8, # 线的透明度 height='50%', width='50%').add_to(m) # 将这条线添加到刚才的区域m内 # 起始点,结束点 for i in range(1, len(locations) - 1): flag = '第' + str(i + 1) + '站' folium.Marker(locations[i], icon=folium.Icon(color='green'), popup=folium.Popup(html=parse_zhch(flag), max_width=100)).add_to(m) folium.Marker(locations[0], popup=folium.Popup(html=parse_zhch('起点'), max_width=100), icon=folium.Icon(color='red')).add_to(m) folium.Marker(locations[len(locations) - 1], popup=folium.Popup(html=parse_zhch('终点'), max_width=100), icon=folium.Icon(color='red')).add_to(m) title_html = f'''<h3 align="center" style="font-size:20px"> <b>HNU Trajectory maps for <span style="color:#FF8800 ">{user_id}</span> on <span style="color:#FF8800 ">{str(startTime)}</span> - <span style="color:#FF8800 ">{str(endTime)}</span></b></h3>''' m.get_root().html.add_child(folium.Element(title_html)) file_name = user_id + ".html" m.save(os.path.join(output_path, file_name)) # 将结果以HTML形式保存到指定路径
def get_route(source, destination, date, departure_time, holiday): day = date.day time_period = get_time_period(departure_time.hour) dow = date.weekday() driving_data = get_driving_route(source, destination) summary = driving_data['features'][0]['properties']['summary'] distance = summary['distance'] input = [ day, time_period, dow, source[1], source[0], destination[1], destination[0], distance, holiday ] travel_time = round(regressor.predict([input])[0] / 60) ors_travel_time = round(summary['duration'] / 60) route = driving_data['features'][0]['geometry']['coordinates'] def swap(coord): coord[0], coord[1] = coord[1], coord[0] return coord route = list(map(swap, route)) m = folium.Map(location=[(source[0] + destination[0]) / 2, (source[1] + destination[1]) / 2], zoom_start=13) tooltip = 'Model predicted time = {} mins, \ Default travel time = {} mins'.format(travel_time, ors_travel_time) folium.PolyLine(route, weight=8, color='blue', opacity=0.6, tooltip=tooltip).add_to(m) folium.Marker(location=(source[0], source[1]), icon=folium.Icon(icon='play', color='green')).add_to(m) folium.Marker(location=(destination[0], destination[1]), icon=folium.Icon(icon='stop', color='red')).add_to(m) st.write("Expected travel time is: ", travel_time, "minutes") folium_static(m)
def save_bbox(bbox_tuple, file, tiles=TILES[0], color='red'): """ Save bbox as file .html using Folium. Parameters ---------- bbox_tuple : tuple. Represents a bound box, that is a tuple of 4 values with the min and max limits of latitude e longitude. file : String. Represents filename. tiles : String, optional, default 'OpenStreetMap'. Represents tyles'srs type_. Example: 'openstreetmap', 'cartodbpositron', 'stamentoner', 'stamenterrain', 'mapquestopen', 'MapQuest Open Aerial', 'Mapbox Control Room' and 'Mapbox Bright'. color : String, optional, default 'red'. Represents color of lines on map. Examples -------- >>> from pymove.trajectories import save_bbox >>> bbox = (22.147577, 113.54884299999999, 41.132062, 121.156224) >>> save_bbox(bbox, 'bbox.html') """ m = folium.Map(tiles=tiles) m.fit_bounds([[bbox_tuple[0], bbox_tuple[1]], [bbox_tuple[2], bbox_tuple[3]]]) points_ = [ (bbox_tuple[0], bbox_tuple[1]), (bbox_tuple[0], bbox_tuple[3]), (bbox_tuple[2], bbox_tuple[3]), (bbox_tuple[2], bbox_tuple[1]), (bbox_tuple[0], bbox_tuple[1]), ] folium.PolyLine(points_, weight=3, color=color).add_to(m) m.save(file)
def insertBikePath(map, path, type, direction, quality, popupLegend): color = None if quality == 4: color = 'blue' elif quality == 3: color = 'green' elif quality == 2: color = 'yellow' elif quality == 1: color = 'orange' elif quality == 0: color = 'red' else: color = 'grey' dash_array = 0 if type == 0: dash_array = 20 elif type == 1: dash_array = 10 popup = folium.Popup(popupLegend, max_width=180, min_width=180) folium.PolyLine(path, color=color, weight=8, opacity=0.5, popup=popup, dash_array=dash_array).add_to(map) arrows = list() if direction == 0: arrows = getArrows([path[0], path[1]], color) arrows = arrows + getArrows([path[1], path[0]], color) elif direction == 1: arrows = getArrows([path[0], path[1]], color) elif direction == 2: arrows = getArrows([path[1], path[0]], color) for arrow in arrows: arrow.add_to(map)
def FlightTracks(m, flight): fg = folium.FeatureGroup(name="Flight Tracks") m.add_child(fg) for ilayer, layer in enumerate(flight): if parser.args.relative: label = "AGL: " + length_label(layer.avg_height) else: label = "MSL: " + length_label(layer.avg_elev) color = getColor() print(label) lg = plugins.FeatureGroupSubGroup(fg, label) m.add_child(lg) folium.PolyLine(locations=layer.path, popup=label, color=color).add_to(lg) for ipath, loc in enumerate(layer.path): if ipath == 0: continue folium.CircleMarker(location=loc, radius=5, weight=8. / ipath, popup=label, color=color).add_to(lg)
def test_polyline_text_path(): m = folium.Map([20., 0.], zoom_start=3) wind_locations = [[59.355600, -31.99219], [55.178870, -42.89062], [47.754100, -43.94531], [38.272690, -37.96875], [27.059130, -41.13281], [16.299050, -36.56250], [8.4071700, -30.23437], [1.0546300, -22.50000], [-8.754790, -18.28125], [-21.61658, -20.03906], [-31.35364, -24.25781], [-39.90974, -30.93750], [-43.83453, -41.13281], [-47.75410, -49.92187], [-50.95843, -54.14062], [-55.97380, -56.60156]] wind_line = folium.PolyLine(wind_locations, weight=15, color='#8EE9FF') attr = {'fill': '#007DEF', 'font-weight': 'bold', 'font-size': '24'} wind_textpath = plugins.PolyLineTextPath(wind_line, ') ', repeat=True, offset=7, attributes=attr) m.add_child(wind_line) m.add_child(wind_textpath) out = normalize(m._parent.render()) # We verify that the script import is present. script = '<script src="https://rawcdn.githack.com/makinacorpus/Leaflet.TextPath/leaflet0.8-dev/leaflet.textpath.js"></script>' # noqa assert script in out # We verify that the script part is correct. tmpl = Template(""" {{ this.polyline.get_name() }}.setText( "{{this.text}}", {{ this.options|tojson }} ); """) expected = normalize(tmpl.render(this=wind_textpath)) assert expected in out
def folium_plot_bbox(bbox_tuple, tiles='OpenStreetMap', color='red', save=False, filename='bbox_.html'): m = folium.Map( tiles=tiles ) # tiles = OpenStreetMap, mapquestopen, MapQuest Open Aerial, Mapbox Bright, Mapbox Control Room, stamenterrain, stamentoner, stamenwatercolor, rra, cartodbdark_matter m.fit_bounds([[bbox_tuple[0], bbox_tuple[1]], [bbox_tuple[2], bbox_tuple[3]]]) tnz_points_ = [(bbox_tuple[0], bbox_tuple[1]), (bbox_tuple[0], bbox_tuple[3]), (bbox_tuple[2], bbox_tuple[3]), (bbox_tuple[2], bbox_tuple[1]), (bbox_tuple[0], bbox_tuple[1])] polygon = folium.PolyLine(tnz_points_, weight=3, color=color) polygon.add_to(m) if save == True: m.save(filename) return m, polygon
def get_beautiful_base_image_map(df_flux, thin=False): """ Create the beautiful folium map containing routes, with blur effect """ # Initialize folium map parameters folium_map = folium.Map(location=sgs._location_map, zoom_start=sgs._zoom_map, tiles="CartoDB dark_matter") # From outer to inner, establish a beautiful shading of colors and opacities in order # to create a lightning effect colors = ['#FFCB00', '#FFD325', '#FDFAF1'] weight = 1 # The thin mode allow to draw a very light network, which is useful if you want to add # other information of the map in order to avoid to overload the representation if thin: opacities = [.12, .16, .55] weight = 1 / 20 else: opacities = [.18, .23, .8] weight = 1 / 5 # The process is doubled because of a bug from folium which sometimes doesn't draw the line for j in range(2): # Iterate on all routes to draw for ind_, row in df_flux.iterrows(): # Iterate over the successive layers of colors/weights/opacities which result in the lightning effect for i in range(len(colors)): # Add a line on the folium map folium.PolyLine(locations=[[row[4], row[5]], [row[1], row[2]]], color=colors[i], opacity=float(opacities[i]), weight=np.log2(row['flux']) * (len(colors) - i) * weight).add_to(folium_map) return folium_map
def draw_gps(locations, file_name): """ 绘制gps轨迹图 :param locations: list, 需要绘制轨迹的经纬度信息,格式为[[lat1, lon1], [lat2, lon2], ...] :param output_path: str, 轨迹图保存路径 :param file_name: str, 轨迹图保存文件名 :return: None """ m = folium.Map(locations[0], zoom_start=15, attr='default') # 中心区域的确定 folium.PolyLine( # polyline方法为将坐标用线段形式连接起来 locations, # 将坐标点连接起来 weight=3, # 线的大小为3 color='orange', # 线的颜色为橙色 opacity=0.8 # 线的透明度 ).add_to(m) # 将这条线添加到刚才的区域m内 # 起始点,结束点 folium.Marker(locations[0], popup='<b>Starting Point</b>').add_to(m) folium.Marker(locations[-1], popup='<b>End Point</b>').add_to(m) m.save(file_name) # 将结果以HTML形式保存到指定路径
def plotSelectedODRoutes(): s=folium.Map(location=[53.235048, -1.421629], zoom_start=13) sql="SELECT * FROM OtoM WHERE odrouteid='MAC000010101>MAC000010104>MAC000010119' \ OR odrouteid='MAC000010101>MAC000010118>MAC000010119';" df_links = gpd.GeoDataFrame.from_postgis(sql,con,geom_col='the_geom') df_links.to_csv('df_links.csv') for i in range(0,df_links.shape[0]): link = df_links.iloc[i] lons = link['the_geom'].coords.xy[0] #coordinates in latlon lats = link['the_geom'].coords.xy[1] #gid = int(link.gid) lon=[];lat=[] n_segments = len(lons) for j in range(0, n_segments): (a,b)=(lons[j], lats[j]) lon.append(a) lat.append(b) loc=[[lat],[lon]] #locations=[[-1.4219618, 53.2309453], [-1.421946, 53.2308295], [-1.4220285, 53.2307102]] folium.PolyLine(locations=loc, color='red', \ weight=5).add_to(s) s.save("chesterfield55.html")
def add_OD_Line(my_map, leg, line_color="blue", line_weight=0.5, line_opacity=0.5, tooltip_text="", mark_destination=True): p1 = [leg.origin[0], leg.origin[1]] p2 = [leg.destination[0], leg.destination[1]] #print ([p1, p2]) folium.PolyLine(locations=[p1, p2], color=line_color, weight=line_weight, opacity=line_opacity, smooth_factor=1, stroke=True, line_join="miter", fill=False, fill_opacity=1, tooltip=folium.Tooltip(tooltip_text)).add_to(my_map) # Mark the destinations with an icon if mark_destination: folium.map.Marker([p2[0], p2[1]], tooltip=folium.Tooltip("destination")).add_to(my_map) if False: # references for icon names: # https://ionicons.com/ # folium.map.Marker( [p2[0], p2[1]], icon=folium.Icon( icon='arrow-down', # arrow-right, arrow-down, info-sign icon_size=(10, 10), icon_color='blue', icon_anchor=(0, 0), ), #size=(2,2), ).add_to(my_map)
def visualization_4(visited, Nodes, coord): # we import and delet it into the func import folium #starting node for center the map starting = coord[visited[0]] mapit = folium.Map(location=[starting[1], starting[0]], zoom_start=10) # coordinates of all nodes Way = [] for i in range(len(Nodes)): v = coord[Nodes[i]] Way.append((v[1], v[0])) #street between vertices folium.PolyLine(Way, color="gray", weight=2.5).add_to(mapit) #plot all the vertices ac circles for i in range(len(Way)): folium.CircleMarker(Way[i], radius=3, opacity=0.1 + 0.9 * ((i + 1) / len(Nodes))).add_to(mapit) #plot the vertices selected by the user for i in range(1, len(visited) - 1): v = coord[visited[i]] folium.Marker((v[1], v[0]), icon=folium.Icon(color='blue', icon='cloud'), radius=8).add_to(mapit) # change color for starting and ending points folium.Marker(Way[0], icon=folium.Icon(color='green', icon='cloud'), radius=8).add_to(mapit) folium.Marker(Way[-1], icon=folium.Icon(color='red', icon='cloud'), radius=8).add_to(mapit) # save map mapit.save(path + 'map.html') # open map on browser webbrowser.open(path + 'map.html', new=2) # We need to removit because otherwise the bulitin map() function doesn't work well del folium
def mapRoutes(routesDF,mapBounds,iBest,iWorst,iFastest,showMarkers): swLat,swLon = mapBounds[0][0],mapBounds[0][1] neLat,neLon = mapBounds[1][0],mapBounds[1][1] mapCenter = [(neLat+swLat)/2.,(neLon+swLon)/2.] m = folium.Map(mapCenter, tiles='CartoDB positron') m.fit_bounds(mapBounds) # is there a way to feed dataframe directly into polylines? for iR, route in routesDF.iterrows(): color='green' if iR==iBest else 'blue' folium.PolyLine(route.polyLines,color=color, tooltip='Route score: %.1f; Nature sightings: %.1f' %(route.score,route.natureCount)).add_to(m) if showMarkers: for iC,coord in enumerate(route.latLons): encoded = base64.b64encode(open(route.imageNames[iC], 'rb').read()).decode('UTF-8') html = '<figure> <img src="data:image/jpg;base64,%s" height=225 width=300/> <figcaption> Image Score: %0.2f </figcaption> </figure>' %(encoded,route.imageScores[iC]) frame=IFrame(html, width=363, height=275) popup = folium.Popup(frame,max_width=410) folium.Marker(coord,popup=popup,icon=folium.Icon(color=color)).add_to(m) return st.markdown(m._repr_html_(), unsafe_allow_html=True)
def requerimiento3(catalog, pais1, pais2): k = 1 g = 1 tr1 = False tr2 = False e1 = None while k <= lt.size(catalog['countries']) and not tr1: p = lt.getElement(catalog['countries'], k) if p['CountryName'].lower() in pais1.lower(): tr1 = True e1 = p k += 1 e2 = None while g <= lt.size(catalog['countries']) and not tr2: f = lt.getElement(catalog['countries'], g) if f['CountryName'].lower() in pais2.lower(): tr2 = True e2 = f g += 1 pa1 = formatVertex(e1['CapitalName'].replace("-", "").lower(), e1['CountryCode']) pa2 = formatVertex(e2['CapitalName'].replace("-", "").lower(), e2['CountryCode']) catalog['rutas'] = djk.Dijkstra(catalog['connections'], pa1) ruta = djk.pathTo(catalog['rutas'], pa2) distancia = djk.distTo(catalog['rutas'], pa2) m = folium.Map(location=[4.6, -74.083333], tiles="Stamen Terrain") ad = ruta for e in lt.iterator(ad): cv = e['vertexA'].split("-", 1) ce = e['vertexB'].split("-", 1) infov = mp.get(catalog['points'], cv[0])['value'] infoe = mp.get(catalog['points'], ce[0])['value'] folium.Marker([float(infov['latitude']), float(infov['longitude'])], popup=str(infov['name'])).add_to(m) folium.Marker([float(infoe['latitude']), float(infoe['longitude'])], popup=str(infov['name'])).add_to(m) folium.PolyLine(locations=[(float(infov['latitude']), float(infov['longitude'])), (float(infoe['latitude']), float(infoe['longitude']))], tooltip=str(cv[1])).add_to(m) m.save('mapa_req3.html') return ruta, distancia
def tencent_rotated_marker(out_dir="../../out"): map_osm = folium.Map(location=[31.32, 120.63], zoom_start=12) locs = [ [31.387113, 120.929393], [31.364861, 120.609265], [31.226864, 120.511118], [31.269273, 120.750024], [31.264751, 120.598769], [31.299345, 120.742185], ] for loc in locs: RotatedMarker(loc, rotation_angle=45).add_to(map_osm) folium.PolyLine(locs, fill_color='high', fill=True, fill_opacity=0.6, stroke=False).add_to(map_osm) file_path = "{}/tencent_rotated_marker.html".format(out_dir) map_osm.save(file_path)
def map(request): #Replace location with avg of bounds in database #68.26% Height fits perfectly in the container and prevents a lot of css-overflow issues which are currently managed by overflow:auto #REPLACE LOCATION AND FILL DATABASE if request.method == 'POST': map1 = folium.Map(location=[19.2120, 72.8567], zoom_start=14) #LOCATION = s.coords+d.coords/2 s = request.POST['source'] d = request.POST['destination'] all_nodes = Nodes.objects.all() s_coords = all_nodes.filter(name=s)[0].latitude, all_nodes.filter( name=s)[0].longitude d_coords = all_nodes.filter(name=d)[0].latitude, all_nodes.filter( name=d)[0].longitude print(s, d) path = Dijkstra_4(s, d) coords = [] for i in path: ob = all_nodes.filter(name=i)[0] coords.append([ob.latitude, ob.longitude]) folium.PolyLine(coords, color='red', weight=4.5).add_to(map1) folium.Marker(s_coords).add_to(map1) folium.Marker(d_coords).add_to(map1) m = map1._repr_html_() return render(request, 'Maps/maps_map.html', {'map': m}) if request.method == 'GET': map1 = folium.Map(location=[19.2120, 72.8567], zoom_start=14) destnodes = DestinationNodes.objects.all() #Destination nodes qs for destnode in destnodes: n = Nodes.objects.filter(name=destnode.name)[0] coord = (n.latitude, n.longitude) folium.Marker(location=coord, popup="NODE ID: " + str(n.name)).add_to(map1) m = map1._repr_html_() return render(request, 'Maps/maps_map.html', {'map': m}) # Proper path not in data for s = 7044039703, d = 7054927767
def main(): pose_file = "highway_data/planar1/reference.json" poses = load_poses(pose_file) xyz = np.array([(pose['x'], pose['y'], pose['z']) for pose in poses]) print() print("XYZ coordinates of the camera trajectory") print(xyz) long_lat_height = np.array(to_gps(xyz[:, 0], xyz[:, 1], xyz[:, 2])).T print() print("GPS coordinates of the camera trajectory") print(long_lat_height) # export to maps m = folium.Map(location=long_lat_height[0, :2], zoom_start=13) folium.PolyLine(locations=long_lat_height[:, :2], popup="Planar 1 Reference", color="#000000").add_to(m) m.save("example_3_index.html")
def map(result): nodes = [] for path in result: for n in path: nodes.append(n) coord_list = [] for el in nodes: coord = [-long[el]/1000000,lat[el]/1000000] coord_list.append(coord) #creating the map m = folium.Map(location = centre, zoom_start = 15) for coord in coord_list: if coord != centre: folium.Marker(location = coord, icon=folium.Icon(color = 'red')).add_to(m) folium.PolyLine(nodes, color="red", weight=2.5, opacity=1).add_to(m) return m
def plotRouteToOverLay(G, dfTimetable, routeDesc): routeLayer = FeatureGroup(name=routeDesc, show=False) for iidx in range(len(dfTimetable.index)): stnOrder = dfTimetable.index[iidx] crnStnCode = dfTimetable.at[stnOrder, const.RoutesTtbCols.StationCode.name] coordCrnStn = [ G.nodes[crnStnCode][const.GNodeAttribs.Lat.name], G.nodes[crnStnCode][const.GNodeAttribs.Lng.name] ] # adds marker to bus stops folium.Marker( location=coordCrnStn, tooltip='StationId %d, %s' % (G.nodes[crnStnCode][const.GNodeAttribs.StationId.name], G.nodes[crnStnCode][const.GNodeAttribs.StationDesc.name]), icon=folium.Icon(prefix='fa', icon='bus')).add_to(routeLayer) if iidx == 0: continue # gets pathPoints between crnStnCode and preStnCode prevStnOrder = dfTimetable.index[iidx - 1] preStnCode = dfTimetable.at[prevStnOrder, const.RoutesTtbCols.StationCode.name] edgeRoutes = G.edges[preStnCode, crnStnCode][const.GEdgeAttribs.routes.name] pathPoints = edgeRoutes[const.GEdgeRouteCols.pathPoints.name][0] # notes that coordinates of each path point are in long,lat order, thus need to convert this to lat,long order points = [(point[1], point[0]) for point in pathPoints] # adds polyline of this route to map folium.PolyLine(points, color='red', weight=3, opacity=.3, popup='route info').add_to(routeLayer) return routeLayer
def build_map(user_location: list, df: pd.DataFrame): ''' Build the html map, which consists of 3 layers: main layer with user's location, film labels layer and layer for displaying distance. ''' user_coords = [eval(coord) for coord in user_location[1:]] map = folium.Map(location=user_coords, zoom_start=10) fg_user = folium.FeatureGroup(name='World map') # add main layer and icon with user's coordinates fg_user.add_child( folium.Marker(location=user_coords, popup="Your location", icon=folium.Icon(color='darkred'))) # add layer with locations of films locations = df['coordinates'][:10] films = df['name'][:10] fg_films = folium.FeatureGroup(name='Locations of films') for loc, film in zip(locations, films): fg_films.add_child( folium.Marker(location=loc, popup=film, icon=folium.Icon())) # add layer with distances to film locations fg_distances = folium.FeatureGroup(name='Distances to film location') for loc in locations: fg_distances.add_child( folium.PolyLine([user_coords, loc], color='cadetblue', weight=5, opacity=0.7)) map.add_child(fg_user) map.add_child(fg_films) map.add_child(fg_distances) map.add_child(folium.LayerControl()) map.save('map.html')
def plot_osm_map(track, output_file="map.html"): norm = matplotlib.colors.Normalize(vmin=min(track["speed_kph"]), vmax=max(track["speed_kph"]), clip=True) mapper = cm.ScalarMappable(norm=norm, cmap=cm.plasma) map_ = folium.Map( location=[track["position_lat"][0], track["position_long"][0]], zoom_start=15) for (_, prev), (_, row) in iter_with_prev(track.iterrows()): tooltip = f'{row["speed_kph"]:0.1f}kmh {row["heart_rate"]}bpm {row["altitude"]:0.1f}m' color = matplotlib.colors.to_hex(mapper.to_rgba(row["speed_kph"])) from_ = (prev["position_lat"], prev["position_long"]) to = (row["position_lat"], row["position_long"]) folium.PolyLine( locations=(from_, to), tooltip=tooltip, color=color, opacity=0.8, weight=5, ).add_to(map_) map_.save(output_file)
def get_map_folium(melhor_rota, coords_clientes, nome_mapa): # criando mapa mapa = folium.Map(location=[(melhor_rota['start_point'][0] + melhor_rota['end_point'][0])/2, (melhor_rota['start_point'][1] + melhor_rota['end_point'][1])/2], zoom_start=12) # traçando caminho #print(melhor_rota['polyline']) folium.PolyLine(melhor_rota['route'], weight=8, color='blue', opacity=0.5).add_to(mapa) # plotando inicio e fim folium.Marker(location=melhor_rota['start_point'], tooltip="Início", icon=folium.Icon(icon='play', color='green')).add_to(mapa) folium.Marker(location=melhor_rota['end_point'],tooltip="Final", icon=folium.Icon(icon='stop', color='red')).add_to(mapa) # plotando clientes contagem = 0 for coordenada in coords_clientes: contagem +=1 lat = coordenada.split(',')[0] lng = coordenada.split(',')[1] folium.Marker(location=(lat, lng), popup="Este é o "+str(contagem)+"º waypoint", tooltip=contagem).add_to(mapa) mapa.save(nome_mapa+".html")
def plot_output(args, results: list, tracks_data: dict): """ Plots the similar tracks found and their attributes on an interactive map (kept in the file fol.html) :param args: the command-line arguments we got from the user. :param results: a list containing the ids of the osm-tracks the program decided were similar enough to the user's request. :param tracks_data: a dictionary containing the data we collected over the osm-tracks in the requested area. """ colors_list = [ 'red', 'green', 'orange', 'lightred', 'pink', 'black', 'blue', 'darkpurple', 'darkred', 'cadetblue', 'darkblue', 'darkgreen', 'purple', 'gray' ] # Calculate the center coordinate of the search area and create a map object in this area: location_x = (args.north_lim + args.south_lim) / 2 location_y = (args.west_lim + args.east_lim) / 2 output_map = folium.Map(location=[location_x, location_y], zoom_start=13) # Present the similar tracks on the map: for result_id in results: coors_rel_path = 'areas_databases\\' + args.search_area + '\\tracks_gps_points\\' + result_id df = pd.read_csv( os.path.abspath( os.path.join(os.path.dirname(__file__), '..', coors_rel_path))) points = [(row[0], row[1]) for row in df[['lat', 'lon']].values] folium.PolyLine(points, color=colors_list[int(result_id) % len(colors_list)], opacity=1).add_to(output_map) folium.Marker(location=[points[0][0], points[0][1]], popup='track ' + result_id + '\n' + str(tracks_data[result_id]['attributes']), icon=folium.Icon(color=colors_list[int(result_id) % len(colors_list)], icon='info-sign')).add_to(output_map) output_map.save('recommended_tracks.html')
def drawing_map(result_point, radio=False, distance=False): m = folium.Map(location=[ (lat_start + lat_end) / 2, (lon_start + lon_end) / 2, ], zoom_start=7, tiles='Stamen Terrain') tooltip = 'I am here!' if radio == True | distance == True: folium.CircleMarker(location=[45.58163, -120.15285], radius=100, popup=' FRI ').add_to(m) folium.PolyLine(locations=[(result_point), (45.18163, -120.15285)], line_opacity=0.5).add_to(m) folium.Marker([45.18163, -120.15285], popup='<b>Condon WindFarm</b>', tooltip=tooltip).add_to(m) folium.Marker(result_point, popup='<i>Result</i>', tooltip=tooltip).add_to(m) return m
def plotResults(G, src, res, routes, param): my_map4 = folium.Map(location = [G.nodes[src-1]['attr_dict']['latitude'], G.nodes[src-1]['attr_dict']['longitude']], zoom_start = 12) for s in res: if s == src: icon = 'home' color = 'red' elif s in res: icon = 'map-pin' color = 'blue' else: icon = 'map-marker' color = 'lightgray' folium.Marker([G.nodes[s-1]['attr_dict']['latitude'], G.nodes[s-1]['attr_dict']['longitude']], popup = 'Node '+ str(s), icon=folium.Icon(color=color, icon=icon, prefix='fa') ).add_to(my_map4) old_step_tmp = '' for s_tmp in routes[s]: if old_step_tmp != '': folium.PolyLine(locations = [old_step_tmp, (G.nodes[s_tmp-1]['attr_dict']['latitude'], G.nodes[s_tmp-1]['attr_dict']['longitude'])], line_opacity = 0.5, color = getParamColor(param)).add_to(my_map4) old_step_tmp = (G.nodes[s_tmp-1]['attr_dict']['latitude'], G.nodes[s_tmp-1]['attr_dict']['longitude']) my_map4.save("my_map_new.html") webbrowser.open('file://' + os.path.realpath('my_map_new.html'))
def run(cityposition1,NEW_SIZE): ga = GA(DNA_size=NEW_SIZE, cross_rate=CROSS_RATE, mutation_rate=MUTATE_RATE, pop_size=POP_SIZE) env = TravelSalesPerson(cityposition1) ax = plt.figure(1) for generation in range(N_GENERATIONS): # 主循环 100代 lx, ly = ga.translateDNA(ga.pop, env.city_position) fitness, total_distance = ga.get_fitness(lx, ly) ga.evolve(fitness) best_idx = np.argmax(fitness) # 返回最大的fitness对应的索引 print('Gen:', generation, '| best fit: %.8f' % fitness[best_idx],) env.plotting(np.append(lx[best_idx], lx[best_idx][0]), np.append(ly[best_idx], ly[best_idx][0]), total_distance[best_idx]) # 数据可视化 #最终结果(天选之子) #Lx = lx[best_idx] #Ly = ly[best_idx] Lx = np.append(lx[best_idx], lx[best_idx][0]) Ly = np.append(ly[best_idx], ly[best_idx][0]) result = list(zip(Lx, Ly)) plt.ioff() plt.pause(1) plt.close(ax) #result=run.result # 在地图中显示标记连线 fmap = folium.Map(location=[39.8745, 116.4756], zoom_start=16) for i in range(len(result)): m = folium.Marker(result[i], popup='<b>Skytree</b>') fmap.add_child(child=m) fmap.add_child(folium.PolyLine(locations=result, # 坐标List weight=8)) # 线条宽度 fmap.save('map1.html')