def plot(self, mask=None, segment_ids=None, zoom=12): """Plot ride segments on map in Jupyter Notebook :params mask: list of booleans to select which segments of the ride to map :params segment_ids: index or list of segment ids to select which segments of the ride to map :params zoom: initial zoom level """ if mask and segment_ids: raise Exception('Pass either a mask or a list of ids, not both') segments = self.segments if mask: segments = [sgm for i, sgm in enumerate(segments) if mask[i]] elif segment_ids: if not isinstance(segment_ids, list): segment_ids = [segment_ids] segments = [sgm for sgm in segments if sgm['id'] in segment_ids] lats_start = [sgm['lat_start'] for sgm in segments] lons_start = [sgm['lon_start'] for sgm in segments] lats_end = [sgm['lat_end'] for sgm in segments] lons_end = [sgm['lon_end'] for sgm in segments] median_lat = np.median(lats_start + lats_end) median_lon = np.median(lons_start + lons_end) map = Map(center=(median_lat, median_lon), zoom=zoom) if mask or segment_ids: for sgm in segments: position_start = (sgm['lat_start'], sgm['lon_start']) position_end = (sgm['lat_end'], sgm['lon_end']) poly_line = Polyline( locations=(position_start, position_end), color="red", fill=False, weight=3 ) map.add_layer(poly_line) else: positions = [ (sgm['lat_start'], sgm['lon_start']) for sgm in segments ] positions.append((segments[-1]['lat_end'], segments[-1]['lon_end'])) poly_line = Polyline( locations=positions, color="red", fill=False, weight=3 ) map.add_layer(poly_line) return map
def visualize_sequence_on_map(self, sequence: list): """ Visualizes the resulting sequence of cities on a open source map. :param sequence: list [int] :return: """ self.sequence = sequence # Get Marker positions and create map with markers: markers = self._create_markers(sequence) m = Map(center=markers[0].location, zoom=7, scroll_wheel_zoom=True) marker_cluster = MarkerCluster(markers=markers) m.add_layer(marker_cluster) # Create line between cities: line = Polyline(locations=[x.location for x in markers], color="red", fill=False) m.add_layer(line) m.layout.width = '100vw' m.layout.height = '100vh' # Save file and show in webbrowser: fname = "utils/tmp/map.html" realpath = os.path.realpath(fname) m.save(fname) # webbrowser.open_new_tab(fname) webbrowser.open_new_tab("file://" + realpath) print( "...Opening interactive streetmap in browser. If browser does not show the map correctly, try opening " "the saved HTML-file ({n}) manually.".format(n=realpath))
def Prod_Polyline(df, G): """ Identique à Prod_Ant_Path, les polylines sont plus légère à l'affichage. """ max_ant = list(G.edges.data('freq'))[0][2] pal = sns.color_palette('rainbow', max_ant + 1) line = {} for indice in list(G.edges.data('freq')): x = indice[0] ori = [df.loc[indice[0]].latitude, df.loc[indice[0]].longitude] des = [df.loc[indice[1]].latitude, df.loc[indice[1]].longitude] line[indice] = Polyline( locations=[ori, des], color=pal.as_hex()[x % (max_ant + 1)] #Couleur , fill=False, stroke=True #Bordure , opacity=1.0, weight=2 #largeur en pixel #,fill_color = None #couleur du remplissage #,fill_opacity = 0.2 #opacité du remplissage #,dash_array = None #,line_cap = 'round' #,line_join = 'round' #,name='' ) return line
def add_route_to_map(route, some_map, color='blue'): """ Add a route from the HERE REST API to the given map. This includes markers for all points where a maneuver is needed, like 'turn left'. And it includes a path with lat/lons from start to end and little circle markers around them. """ path_positions = list(chunks(route[0]['shape'], 2)) maneuvers = {(man['position']['latitude'], man['position']['longitude']): man['instruction'] for man in route[0]['leg'][0]['maneuver']} polyline = Polyline(locations=path_positions, color=color, fill=False) some_map += polyline for lat, lon in path_positions: if (lat, lon) in maneuvers: some_map += CircleMarker(location=(lat, lon), radius=2) marker = Marker(location=(lat, lon), draggable=False) message1 = HTML() message1.value = maneuvers[(lat, lon)] marker.popup = message1 some_map += marker else: some_map += CircleMarker(location=(lat, lon), radius=3)
def flightplan_leaflet( flightplan: "FlightPlan", **kwargs ) -> Optional[Polyline]: """Returns a Leaflet layer to be directly added to a Map. .. warning:: This is only available if the Leaflet `plugin <plugins.html>`_ is activated. (true by default) The elements passed as kwargs as passed as is to the PolyLine constructor. """ shape = flightplan.shape if shape is None: return None coords: Iterable = list() if isinstance(shape, LineString): coords = list((lat, lon) for (lon, lat, *_) in shape.coords) else: # In case a FlightPlan could not resolve all parts coords = list( list((lat, lon) for (lon, lat, *_) in s.coords) for s in shape ) kwargs = {**dict(fill_opacity=0, weight=3), **kwargs} return Polyline(locations=coords, **kwargs)
def flight_leaflet(flight: "Flight", **kwargs) -> Optional[Polyline]: """Returns a Leaflet layer to be directly added to a Map. .. warning:: This is only available if the Leaflet `plugin <plugins.html>`_ is activated. (true by default) The elements passed as kwargs as passed as is to the PolyLine constructor. Example usage: >>> from ipyleaflet import Map >>> # Center the map near the landing airport >>> m = Map(center=flight.at().latlon, zoom=7) >>> m.add_layer(flight) # this works as well with default options >>> m.add_layer(flight.leaflet(color='red')) >>> m """ shape = flight.shape if shape is None: return None kwargs = {**dict(fill_opacity=0, weight=3), **kwargs} return Polyline(locations=list( (lat, lon) for (lon, lat, _) in shape.coords), **kwargs)
def as_polyline(self, start=None, end=None, **kwargs): # filter points by start and end time points = [ p.lat_lon for p in self.points if (start is None or p.time >= start) and ( end is None or p.time <= end) ] lines = [] # reversed so as not to interrupt the iteration when we reassign points for i in reversed(range(1, len(points))): lat_1, lon_1 = points[i] lat_2, lon_2 = points[i - 1] # if this pair of points crosses the antimeridian, break the track # into two tracks, one on each side of the globe, with an artificial # point added (m, the middle point) at the antimeridian if abs(lon_1 - lon_2) > 180: if lon_1 > 0: lon_2 += 360. lon_m = 180. else: lon_2 -= 360. lon_m = -180. f = (lon_m - lon_1) / (lon_2 - lon_1) lat_m = lat_1 + f * (lat_2 - lat_1) lines.append([[lat_m, lon_m]] + points[i:]) points = points[0:i] + [[lat_m, -lon_m]] lines.append(points) return Polyline(locations=list(reversed(lines)), **kwargs)
def __get_polyline(self, locations, color='green'): locations_np = np.array(locations.filter(['latitude', 'longitude'])) center = locations_np.mean(axis=0) route = Polyline(locations=locations_np.tolist(), color=color, fill=False) return route, center
def flight_leaflet(flight: Flight, **kwargs) -> Optional[Polyline]: shape = flight.shape if shape is None: return None kwargs = {**dict(fill_opacity=0, weight=3), **kwargs} return Polyline(locations=list( (lat, lon) for (lon, lat, _) in shape.coords), **kwargs)
def draw_map(lat_longs): center = [37.79481, -122.41186] zoom = 12 m = Map(center=center, zoom=zoom, basemap=basemaps.Hydda.Full) m.layout.height = '650px' pl = Polyline(locations=lat_longs) pl.color = path_color.value pl.fill_color = path_color.value m.add_layer(pl) return m
def createLeafletPolyline(m, MapGliderLocation, color='green'): lines = Polyline(locations=MapGliderLocation, color=color, weight=2, stroke=True, opacity=1, line_cap='butt', fill=False) m.add_layer(lines) return m
def plot_rides(rides, how='direction', zoom=10, palette=None): """Plot list of rides on map :params rides: list of BikeRide objects :params how: if 'direction' plot line from start to median position; if 'ride' plot entire ride :params zoom: initial zoom level :params palette: colours to use if plotting rides """ if not palette: palette = PALETTE median_lat = np.median([ride.median_position[0] for ride in rides]) median_lon = np.median([ride.median_position[1] for ride in rides]) m = Map(center=(median_lat, median_lon), zoom=zoom) if how == 'direction': summaries = pd.DataFrame([ ride.summary for ride in rides if not isinstance(ride.summary, str) ]) positions_start = zip(summaries.lat_start, summaries.lon_start) median_positions = [ride.median_position for ride in rides] for pos_start, median_pos in zip(positions_start, median_positions): poly_line = Polyline(locations=(pos_start, median_pos), color="red", fill=False, weight=1) m.add_layer(poly_line) elif how == 'ride': for i, ride in enumerate(rides): colour = palette[i % len(palette)] locations = [(rec['lat'], rec['lon']) for rec in ride.records] poly_line = Polyline(locations=locations, color=colour, fill=False, weight=3) m.add_layer(poly_line) return m
def flight_map(self, center=None, basemap=None, zoom=8): """Display interactive map of the flight path. (Jupyter notebook only.) Parameters ---------- center: tuple, optional (latitude, longitude) center of the map. The default is the average of the flight's lat/lon bounding box. basemap: str, or list or tuple of str, optional Name of the base map available in ipyleaflet. Default: ``('Esri.WorldImagery', 'OpenTopoMap')``. zoom: int, optional Map zoom level. Default is 8. """ if not display_map: raise RuntimeError('Cannot display map') if basemap is None: basemap = ('Esri.WorldImagery', 'OpenTopoMap') elif isinstance(basemap, str): basemap = (basemap, ) elif not isinstance(basemap, (list, tuple)): raise TypeError('basemap is not a str, list, or tuple') base_layers = list() for layer in basemap: name_parts = layer.split('.') base_layer = basemaps for p in name_parts: base_layer = base_layer[p] if not isinstance(base_layer, dict): raise TypeError('base layer not a dict') base_layers.append(basemap_to_tiles(base_layer)) data = self._flight flight_lat = data['latitude'] flight_lon = data['longitude'] if center is None: center = (flight_lat.mean(), flight_lon.mean()) flight_path = Polyline( locations=[np.column_stack((flight_lat, flight_lon)).tolist()], color='blue', fill=False, name='Flight path') flight_map = Map(center=center, zoom=int(zoom)) for _ in base_layers: flight_map.add_layer(_) flight_map.add_layer(flight_path) flight_map.add_control(FullScreenControl()) flight_map.add_control(LayersControl()) display(flight_map)
def get_map_for_linestrings(linestrings, zoom=14): bounds = get_bounds_for_linestrings(linestrings) center_lat = (bounds["min_lat"] + bounds["max_lat"]) / 2 center_lon = (bounds["min_lon"] + bounds["max_lon"]) / 2 center = [center_lat, center_lon] m = Map(center=center, zoom=zoom) max_len = 0 for linestring in linestrings: max_len = max(max_len, len(linestring)) for linestring in linestrings: # intensity = 1 - len(linestring) / max_len # color = "#" + ("{:02x}".format(round(intensity * 255)) * 3) p = Polyline(locations=[point.latlon for point in linestring], fill=False) m += p return m
def __call__(self, meters=1000): if meters not in self.cache: print('loading', meters) url = self.url.format(meters=meters) obj = requests.get(url).json() self.cache[meters] = obj obj = self.cache[meters] isoline = obj['response']['isoline'][0] shape = isoline['component'][0]['shape'] path = [tuple(map(float, pos.split(','))) for pos in shape] if self.isoline: self.the_map -= self.isoline self.isoline = Polyline(locations=path, color='red', weight=2, fill=True) self.the_map += self.isoline
def Get_line(df, pal, color): line = {} for i in range(df.shape[0] - 1): ori = (df.iloc[i].lat, df.iloc[i].lng) des = (df.iloc[i + 1].lat, df.iloc[i + 1].lng) line[i] = Polyline( locations=[ori, des], color=pal.as_hex()[color] #Couleur , fill=False, stroke=True #Bordure , opacity=1.0, weight=1 #largeur en pixel #,fill_color = None #couleur du remplissage #,fill_opacity = 0.2 #opacité du remplissage #,dash_array = None #,line_cap = 'round' #,line_join = 'round' #,name='' ) return line
def visualize(): center = location_latlongs[1] m = Map(center=center, zoom=8) icon1 = Icon( icon_url='https://img.icons8.com/ultraviolet/40/000000/map-pin.png', icon_size=[40, 40], icon_anchor=[20, 40]) icon2 = Icon( icon_url='https://img.icons8.com/officel/40/000000/map-pin.png', icon_size=[40, 40], icon_anchor=[20, 40]) icon3 = Icon( icon_url= 'http://icons.iconarchive.com/icons/custom-icon-design/flatastic-6/256/Circle-icon.png', icon_size=[10, 10], icon_anchor=[5, 5], shadow_size=[5, 5]) line = Polyline(locations=[[ path_latlongs, ]], color="#669df6", fill=False, weight=2, stroke=True) m.add_layer(line) style = {'text-align': 'left', 'description_width': '150px'} i = 0 while i < len(location_latlongs): if i == 0: message = HTML() message.placeholder = "Source" message.description = "Source" + "<br>Node ID: " + location_latlongs[ i][2] + "<br>Lat: " + str( location_latlongs[i][1]) + "<br>Long: " + str( location_latlongs[i][0]) message.style = style marker = Marker(location=location_latlongs[i], draggable=False, title="Source", icon=icon1, rise_on_hover=True, z_index_offset=100) m.add_layer(marker) marker.popup = message elif (len(location_latlongs) - i) == 1: message = HTML() message.placeholder = "Destination" message.description = "Destination" + "<br>Node ID: " + location_latlongs[ i][2] + "<br>Lat: " + str( location_latlongs[i][1]) + "<br>Long: " + str( location_latlongs[i][0]) message.style = style marker = Marker(location=location_latlongs[i], draggable=False, title="Destination", icon=icon2, rise_on_hover=True) m.add_layer(marker) marker.popup = message else: message = HTML() message.placeholder = "Waypoint" message.description = "Waypoint: " + str( i) + "" + "<br>Node ID: " + location_latlongs[i][ 2] + "<br>Lat: " + str( location_latlongs[i][1]) + "<br>Long: " + str( location_latlongs[i][0]) message.style = style marker = Marker(location=location_latlongs[i], draggable=False, icon=icon3, title="Waypoint", rise_on_hover=True) m.add_layer(marker) marker.popup = message i += 1 return (m)
def travel_time(self, dhdx, n, b, xw=0, yw=0, bnds=None): ''' t : float time [days] dhdx : float hydraulic gradient [m/m] Q : float extraction rate [m^3/s] n : float porosity [-] b : float aquifer thickness [m] theta : float angle between x axis and dominant flow direction xw : float x location of well yw : float y location of well ''' T = 0.05 # get parameters Q = self.widgets['Q'].value / 1.e3 t = self.widgets['t'].value theta = (270 - self.widgets['th'].value) / 180. * 3.1416 dhdx = self.widgets['q'].value / 1.e3 q = dhdx * T / b # compute contour if Q < 1.e-5: # special case, zero pumping xout = np.array([xw]) yout = np.array([yw]) else: # compute dimensionless solution t *= 24 * 3600 # convert days to seconds t0 = 2. * np.pi * q**2 / (b * n * Q) * t x0, y0 = travel_time_dimensionless(t0) x = Q * x0 / (2 * np.pi * q) y = Q * y0 / (2 * np.pi * q) x, y = np.concatenate([x, x[::-1]]), np.concatenate([y, -y[::-1]]) x, y = (np.cos(theta) * x - np.sin(theta) * y, np.sin(theta) * x + np.cos(theta) * y) xout = x + xw yout = y + yw # add or update travel time contour lat, lon = xy2ll(xout, yout, *self.wells[0].location) try: self.tt_line.locations = list(zip(lat, lon)) except AttributeError: self.tt_line = Polyline(locations=list(zip(lat, lon)), color='red', fill=False, weight=2) self.add_layer(self.tt_line) # add or update piezometric surface if bnds is None: bnds = self.bounds if len(bnds) == 0: bnds = ((-43.53118921794094, 172.62774467468262), (-43.506293197337435, 172.70936965942383)) ps, ts = self.TheisContours(T, [Q], bnds, [dhdx, theta], levels=np.arange(-10, 20, 1)) try: self.update_contours(ps, ts) except AttributeError: self.ps0 = ps for polygons in self.ps0: self.add_layer(polygons)
type_line= "Ant" # type de ligne pour la trajectoire (toute autre avaleur que "Ant" produit une "PolyLine") if type_line == "Ant": line= AntPath( locations= l, dash_array=[1, 10], delay=2000, color='red', pulse_color='black' ) else: line = Polyline( locations=l, color="red" , fill=False, weight=3 ) m.add_control(FullScreenControl()) m.add_layer(line) # ### Quelques calculs: ### # # - Les distances entre les points successifs. C'est un service fourni par geopy (géodésiques sur l'ellipsoïde terrestre). # - La distance globale porcourue. # - Un "marker" tous les "delta" mêtres. delta=1000. # 1 km.
def layer(self): return Polyline(locations=self.coordinates, color="orange", fill=False)