Example #1
0
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)
Example #2
0
def drawPOIS(POIS, zoom=12):
    centerLat, centerLog = 0, 0

    # taking the average of all latitude and longitude of all the POIs
    # to get the center of the map

    for poi in POIS:
        centerLat += poi.coordinates[0]
        centerLog += poi.coordinates[1]
    centerLat /= len(POIS)
    centerLog /= len(POIS)
    center = (centerLog, centerLat)

    m = Map(center=center, zoom=zoom, close_popup_on_click=False)

    # creating the popup messages on the markers
    # with the name of the POI
    for poi in POIS:
        name = poi.address.split(",")[0]
        marker = Marker(location=poi.coordinates[::-1])
        text = HTML()
        text.value = f"{name}"
        marker.popup = text
        m.add_layer(marker)

    return m
Example #3
0
 def build_map(self, click_handler):
     mean_lat = self.x_data[self.lat_key].values.mean()
     mean_lng = self.x_data[self.lon_key].values.mean()
     # create the map
     m = Map(center=(mean_lat, mean_lng), zoom=4, basemap=basemaps.Stamen.Terrain)
     m.layout.height = '600px'
     # show trace
     markers = []
     for k in self.marker_info:
         lat, lon = k
         message = HTML()
         message.description = "Station ID"
         message.value = str(self.marker_info[k])
         message.placeholder = ""
         marker = Marker(location=(lat, lon))
         marker.on_click(click_handler)
         marker.popup = message
         markers.append(marker)
     marker_cluster = MarkerCluster(
         markers=markers
     )
     # not sure whether we could register once instead of each marker:
     # marker_cluster.on_click(click_handler)
     m.add_layer(marker_cluster)
     # m.add_control(FullScreenControl())
     return m
Example #4
0
def print_geojson(geojson, limit=100):
    center = None
    j = json.load(StringIO(geojson))
    layer_group = LayerGroup()

    features = j['features']
    if limit is not None:
        features = features[0:limit]

    for f in features:
        location = (f['geometry']['coordinates'][1],
                    f['geometry']['coordinates'][0])
        marker = Marker(location=location)
        marker.popup = HTML(str(f['properties']))
        layer_group.add_layer(marker)
        if not center:
            center = location

    if not center:
        center = (0, 0)

    m = Map(layers=(basemap_to_tiles(basemaps.OpenStreetMap.Mapnik), ),
            center=center,
            zoom=8)

    m.add_layer(layer_group)
    return m
Example #5
0
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)
Example #6
0
 def _handle_map_click(self, **kwargs):
     if kwargs.get("type") == "click":
         loc = kwargs.get("coordinates")
         marker = Marker(location=loc)
         marker.on_move(partial(self._handle_marker_move, marker=marker))
         self.domain_coords.append(loc)
         self.marker_locs[marker] = loc
         self.m.add_layer(marker)
         self._update_domain_render()
Example #7
0
    def _addWaypoint(self):
        # Waypoint
        self._waypointMarker = Marker(location=self._startLocation,
                                      draggable=False)
        self._waypointMarker.observe(self._on_location_changed, 'location')
        self._m.add_layer(self._waypointMarker)

        # Waypoint Popup Message
        self._waypointMessage = HTML()
        self._waypointMarker.popup = self._waypointMessage
Example #8
0
    def show_stations_on_map(self,list_inc,list_process,list_filters,
     opt_params):
        """ Returns an interactive map of source and stations, use only in 
        Jupyter Notebooks.  

        Inputs:
            | list_inc: list of incidents
            | list_process: list of processes, one list per incident
            | list filters: list of filters defined for stations
            | opt_params: optional parameters (dictionary)

        Optional parameters:

        """
                
        records = self._extract_records(list_inc, list_process, list_filters)

        if not records:
            LOGGER.warning("There are no records to satisfy the provided"
             " filters.")
            return

        m = Map(
            basemap=basemap_to_tiles(basemaps.Esri.WorldImagery, "2020-04-08"),
            center = (Station.pr_source_loc[0],Station.pr_source_loc[1]),
            zoom = 8,
            close_popup_on_click=True
        )

        for i in records:
            if not i[0]:
                continue
            lat = i[0].station.lat
            lon = i[0].station.lon
            marker = Marker(location=(lat, lon), draggable=False,
             icon=AwesomeIcon(name="map-pin", marker_color='green',
             icon_color='darkgreen'), opacity=0.8)
            m.add_layer(marker)
            message = HTML()
            message.value = i[0].station.inc_st_name[list_inc[0]]
            marker.popup = message

        m.add_layer(Marker(icon=AwesomeIcon(name="star",
         marker_color='red', icon_color='darkred'),
         location=(Station.pr_source_loc[0],Station.pr_source_loc[1]),
         draggable=False))
        
        return m
Example #9
0
def plot_gps_clusters(ds, user_id:str, zoom=5):
    """
    Plots GPS coordinates

    Args:
        ds (DataStream): datastream object
        user_id (str): uuid of a user
        zoom: min 0 and max 100, zoom map

    """
    pdf = ds_to_pdf(ds, user_id)

    marker_list = []
    center = None
    for index, row in pdf.iterrows():
        if center is None:
            center = [row["latitude"], row["longitude"]]
        marker_list.append(Marker(location=(row["latitude"], row["longitude"])))

    m = Map(center=(center), zoom=zoom)
    marker_cluster = MarkerCluster(
        markers=(marker_list)
    )
    m.add_layer(marker_cluster)
    return m
Example #10
0
 def get_choice(self, x):
     self.show_menu = False
     self.s.close()
     self.m.remove_layer(self.p)
     self.p = None
     choice = x['new']
     if choice == 'Show flow':
         self.show_flow = True
     elif choice == 'Hide flow':
         self.show_flow = False
         self.m.remove_layer(self.io)
         self.io = None
     elif choice == 'Delineate watershed':
         self.show_flow = False
         self.m.remove_layer(self.io)
         self.io = None
         self.label.value = 'Delineating watershed, please wait...'
         delineate(*self.coord)
         self.label.value = 'Watershed delineated'
         ds_mask = xr.open_zarr('tmp/ds_mask/0').compute()
         mask = ds_mask['mask'].values
         polygon = get_polygon(mask, ds_mask.lat.values[0] + 0.5 / 1200,
                               ds_mask.lon.values[0] - 0.5 / 1200)
         self.m.add_layer(polygon)
         self.label.value = 'Watershed displayed'
     elif choice == 'Set marker':
         if self.marker is not None:
             self.m.remove_layer(self.marker)
         self.marker = Marker(location=self.coord)
         self.m.add_layer(self.marker)
     elif choice == 'Close':
         pass
Example #11
0
    def __init__(self):
        self.url_wms = 'http://wms.geosampa.prefeitura.sp.gov.br/geoserver/geoportal/wms'
        self.wms = WebMapService(self.url_wms, version='1.3.0')
        self.coords_wgs84 = [-23.545567989349365, -46.6351979970932]
        self.center = self.coords_wgs84

        self.mapa_base = WMSLayer(
            url = self.url_wms,
            layers = 'MapaBase_Politico',
            format = 'image/png',
            transparent = True,
            attribution = 'GeoSampa'
        )

        self.lotes = WMSLayer(
            url = 'http://wms.geosampa.prefeitura.sp.gov.br/geoserver/geoportal/wms',
            layers = 'lote_cidadao',
            format = 'image/png',
            transparent = True,
            attribution = 'GeoSampa'
        )

        self.transformer = Transformer.from_crs(31983, 4326)

        self.marker = Marker(location=self.center, draggable=True)

        self.shape = ''
Example #12
0
def point_leaflet(point: PointMixin, **kwargs) -> Marker:

    default = dict()
    if hasattr(point, "name"):
        default["title"] = point.name

    kwargs = {**default, **kwargs}
    return Marker(location=(point.latitude, point.longitude), **kwargs)
Example #13
0
 def layer(self):
     icon = AwesomeIcon(name='camera',
                        marker_color='blue',
                        icon_color='white')
     return Marker(icon=icon,
                   location=(self.location.latitude,
                             self.location.longitude),
                   draggable=False)
Example #14
0
 def load_data(self):
     # Put a marker on the map for each station
     for i, station in enumerate(tqdm(self.stations)):
         marker = Marker(location=(float(get_station_attr(station, 'lat')), 
                                   float(get_station_attr(station, 'lon'))), 
                         draggable=False)
         self.markers[i] = marker
         
     marker_cluster = MarkerCluster(markers=self.markers)
     self.map.add_layer(marker_cluster)
Example #15
0
File: vgan.py Project: cyhsu/vgan
def createLeafletMarker(m, mission, MapGliderLocation, popup=None):
    icon1 = AwesomeIcon(name='paper-plane-o',
                        marker_color='red',
                        icono_color='black',
                        icon_size=(2, 2),
                        spin=False)

    marker = Marker(
        icon=icon1,
        name=mission,
        location=(MapGliderLocation[-1][0], MapGliderLocation[-1][1] - 0.001),
        draggable=False,
        opacity=0.3,
        rise_on_hover=True,
    )
    if popup:
        marker.popup = widgets.HTML('<h1><u>{}</u></h1>'.format(mission))
    m.add_layer(marker)
    return m
Example #16
0
	def showonmap(self):
		try:
			from ipyleaflet import Map, Marker
		except ModuleNotFoundError:
			print('Non riesco ad importare i moduli.')
		poi = (self.data['Location']['Y'],self.data['Location']['X'])
		m = Map(center=poi, zoom=15)
		marker = Marker(location=poi, draggable=True)
		m.add_layer(marker);
		display(m)
Example #17
0
def base_map(area, source):
    from ipyleaflet import Map, Marker

    center, zoom = centroid(area, source)

    m = Map(center=center, zoom=zoom)

    base_map.map_marker = Marker(location=m.center)
    m += base_map.map_marker

    return m
    def Location(self):
        # Import pra tratamento das coordenadas

        self.results = geocoder.geocode(u'Brussels, Belgium')
        self.center = (self.results[0]['geometry']['lat'],
                       self.results[0]['geometry']['lng'])

        map = Map(center=self.center, zoom=6)
        self.marker = Marker(location=self.center, draggable=False)
        map.add_layer(self.marker)
        map
Example #19
0
    def update_contours(self, ps, ts):
        for p, p0 in zip(ps, self.ps0):
            p0.locations = p.locations

        [self.remove_layer(tk) for tk in self.contour_labels]

        self.contour_labels = []
        for ti in ts:
            i = DivIcon(html=ti._text + '&nbsp;m')
            tsm = Marker(location=[ti._x, ti._y], icon=i)
            self.add_layer(tsm)
            self.contour_labels.append(tsm)
Example #20
0
def Give_Marker_Cluster(df):
    markers = []
    for i in df.index:
        x = df.loc[i][df.columns[0]]
        y = df.loc[i][df.columns[1]]
        name = str(i)
        markers.append(
            Marker(location=(x, y),
                   draggable=False,
                   title=str(round(x, 3)) + str(round(y, 3))))

    return MarkerCluster(markers=(markers))
Example #21
0
def point_leaflet(point: "PointMixin", **kwargs) -> Marker:
    """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 Marker constructor.
    """

    default = dict()
    if hasattr(point, "name"):
        default["title"] = point.name

    kwargs = {**default, **kwargs}
    marker = Marker(location=(point.latitude, point.longitude), **kwargs)

    label = HTML()
    label.value = repr(point)
    marker.popup = label

    return marker
Example #22
0
def drawRoute(route, zoom=12):
    # getting the center of the route
    m = Map(center=route[len(route) // 2], zoom=zoom)

    # mark the source node coordinates
    src_marker = Marker(location=route[0], draggable=False)
    m.add_layer(src_marker)

    # mark the destination node coordinates
    dest_marker = Marker(location=route[len(route) - 1], draggable=False)
    m.add_layer(dest_marker)

    # draw AntPath between every two consecutive nodes
    for u, v in zip(route[0:], route[1:]):
        step = map(list, [u, v])
        step_path = AntPath(locations=[*step],
                            dash_array=[1, 10],
                            delay=1000,
                            color='black',
                            pulse_color='red')
        m.add_layer(step_path)

    return m
Example #23
0
 def build_map(self, click_handler: Callable[[Dict[str, Any]],
                                             None]) -> Map:
     mean_lat = self.x_data[self.lat_key].values.mean()
     mean_lng = self.x_data[self.lon_key].values.mean()
     # create the map
     m = Map(center=(mean_lat, mean_lng),
             zoom=4,
             basemap=basemaps.Stamen.Terrain)
     m.layout.height = '1200px'
     # show trace
     markers = []
     for k in self.marker_info:
         message = self.create_popup(k)
         marker = Marker(location=k, draggable=False)
         marker.on_click(click_handler)
         marker.popup = message
         markers.append(marker)
     marker_cluster = MarkerCluster(markers=markers)
     # not sure whether we could register once instead of each marker:
     # marker_cluster.on_click(click_handler)
     m.add_layer(marker_cluster)
     # m.add_control(FullScreenControl())
     return m
Example #24
0
def Give_Colored_Marker(df, Station, icone):
    """
    Cette fonction permet de produire tous les marquers associés au station fourni dans le Graph.
    On s'appuye sur le DataFrame donné pour trouver les stations,leur nom et leurs coordonées
    """
    markers = []
    for indice in Station:
        markers.append(
            Marker(location=(df.loc[indice].latitude,
                             df.loc[indice].longitude),
                   draggable=False,
                   title=df.loc[indice].Station_Name,
                   icon=icone))
    return tuple(markers)
Example #25
0
def Give_Marker_Cluster(df):
    """
    Cette fonction permet de produire une clustered Marquer afin d'affichier l'ensemble des stations
    du DataFrame.
    Les stations se regroupent en fonction du zoom
    """
    markers = []
    for i in df.index:
        x = df.loc[i].latitude
        y = df.loc[i].longitude
        name = df.loc[i].Station_Name
        markers.append(Marker(location=(x, y), draggable=False, title=name))

    return MarkerCluster(markers=(markers))
Example #26
0
    def _create_markers(self, sequence: list) -> List[Marker]:
        """
        Creates markers in the needed structure/object.
        :param sequence: list [int]

        :return: list [Marker]
        """
        markers = []
        for s in sequence:
            markers.append(
                Marker(location=(self.dataframe["Breitengrad"][s],
                                 self.dataframe["Längengrad"][s]),
                       title=self.dataframe["msg Standort"][s],
                       draggable=False))
        return markers
Example #27
0
 def add_points_from_csv(self,
                         in_csv,
                         x="longitude",
                         y="latitude",
                         label=None,
                         layer_name="Marker cluster"):
     # COME BACK TO THIS: https://carpentries-incubator.github.io/jupyter_maps/03-vector/index.html
     # TO-DO: ADD POP UPS
     points = csv_to_geojson(in_csv=in_csv, x=x, y=y)
     markers = [
         Marker(location=record['geometry']['coordinates'])
         for record in points['features']
     ]
     marker_cluster = MarkerCluster(markers=markers, name=layer_name)
     self.add_layer(marker_cluster)
Example #28
0
def plot_locations(alamat):
    # location address
    location = geocoder.osm(alamat)

    # latitude and longitude of location
    latlng = [location.lat, location.lng]

    # create map
    plot_locations_map = Map(center=latlng, zoom=16)

    # marker
    marker = Marker(location=latlng, title=str(alamat))
    plot_locations_map.add_layer(marker)

    # display map
    display(plot_locations_map)
Example #29
0
 def _addControls(self):
     # Add Controls
     self._m.add_control(
         MeasureControl(position='bottomleft',
                        active_color='orange',
                        primary_length_unit='kilometers'))
     self._m.add_control(FullScreenControl())
     self._m.add_control(ScaleControl(position='bottomleft'))
     searchMarker = Marker(icon=AwesomeIcon(
         name="check", marker_color='green', icon_color='darkred'))
     self._m.add_control(
         SearchControl(
             position="topleft",
             url=
             'https://nominatim.openstreetmap.org/search?format=json&q={s}',
             zoom=self._zoom,
             marker=searchMarker))
Example #30
0
def Give_Marker(df, G):
    """
    Cette fonction permet de produire tous les marquers associés au station fourni dans le Graph.
    On s'appuye sur le DataFrame donné pour trouver les stations,leur nom et leurs coordonées
    """
    markers = []

    for indice in list(G.nodes):
        ###############ICI MA MODIF NICO###################################
        #if indice in df.index:
        ###############ICI MA MODIF NICO###################################
        markers.append(
            Marker(location=(df.loc[indice].latitude,
                             df.loc[indice].longitude),
                   draggable=False,
                   title=df.loc[indice].Station_Name))
    return tuple(markers)
Example #31
0
def Give_Colored_Marker(df, color='blue', type='d'):
    if type == 'b':
        name = 'fa-podcast'
    elif type == 'd':
        name = 'fa-user-circle-o'
    else:
        name = 'fa-user-circle-o'

    icon1 = AwesomeIcon(name=name, marker_color=color, spin=False)

    markers = []
    for i in df.index:
        x = df.loc[i][df.columns[0]]
        y = df.loc[i][df.columns[1]]
        name = str(i)
        markers.append(
            Marker(icon=icon1, location=(x, y), draggable=False, title=name))

    return markers