def __init__(self, center=(41.8204600, 1.8676800), zoom=9): self.map = Map(center=center, zoom=zoom, basemap=basemaps.OpenStreetMap.HOT) polygon = Polygon(locations=[[]], color="green", fill_color="green") def handle_click(**kwargs): if kwargs.get('type') == 'click': pol = next(layer for layer in self.map.layers if isinstance(layer, Polygon)) coords = kwargs.get('coordinates') if (len(polygon.locations) == 0): pol.locations[0].extend([coords, coords]) else: pol.locations[0].insert(1, coords) self.map.remove_layer(pol) other = Polygon(locations=pol.locations, color="green", fill_color="green") self.map.add_layer(other) if kwargs.get('type') == 'contextmenu': pol = next(layer for layer in self.map.layers if isinstance(layer, Polygon)) self.map.remove_layer(pol) other = Polygon(locations=[[]], color="green", fill_color="green") self.map.add_layer(other) self.map.on_interaction(handle_click) self.map.add_layer(polygon) display(self.map)
def polygon_map(area, source): from ipyleaflet import Map, DrawControl center, zoom = centroid(area, source) m = Map(center=center, zoom=zoom) draw_control = DrawControl() draw_control.polygon = { "shapeOptions": { "fillColor": "#6be5c3", "color": "#6be5c3", "fillOpacity": 1.0 }, "drawError": { "color": "#dd253b", "message": "Oups!" }, "allowIntersection": False } polygon_map.feature_collection = { 'type': 'FeatureCollection', 'features': [] } def handle_draw(self, action, geo_json): """Do something with the GeoJSON when it's drawn on the map""" polygon_map.feature_collection['features'].append(geo_json) draw_control.on_draw(handle_draw) m.add_control(draw_control) return m
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
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
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
def draw_interactive_map(): """ Draws interactive map to be able to draw/define a region of interest """ wms_drillholes = WMSLayer( url='http://geo.loop-gis.org/geoserver/loop/wms?', layers='loop:collar_4326', format='image/png', transparent=True, attribution='Drilhole collar from GSWA', name='drillhole collars' ) wms_geol = WMSLayer( url='http://geo.loop-gis.org/geoserver/loop/wms?', layers='loop:2_5m_interpgeop15_4326', format='image/png', transparent=True, opacity=0.4, attribution='Geology data from GSWA', name='geology' ) m =Map(basemap=basemaps.OpenTopoMap, center=(-29,116.5), zoom=8,scroll_wheel_zoom=True) m.add_layer(wms_geol) m.add_layer(wms_drillholes) m.add_control(LayersControl()) dc = DrawControl(rectangle={'shapeOptions': {'color': '#0000FF'}}) m.add_control(dc) m
def __init__(self, position: str = "bottomleft", attr_name: str = "style", kind: str = "stroke", orientation: str = "horizontal", transparent: bool = False, a_map: Map = None, layer: Layer = None, place_control: bool = True): def updated(change): """Called after each single-letter edit of the JSON in the textarea. """ if change["type"] != "change": return value = change["owner"].value if not is_valid_json(value): return else: layer.style = json.loads(value) def close(button): a_map.remove_control(wc) layout = Layout(width="28px", height="28px", padding="0px 0px 0px 4px") btn = Button(tooltip="Close", icon="close", layout=layout) btn.on_click(close) ta = Textarea(value=json.dumps(getattr(layer, attr_name), indent=2)) ta.layout.width = "200px" ta.observe(updated) header = HBox([HTML(f"<i>{attr_name} (JSON)</i>"), btn]) ui = VBox([header, ta]) wc = WidgetControl(widget=ui, position=position, transparent_bg=True) a_map.add_control(wc)
def ipyleaflet_scatterplot_per_class( x, y, center=(0, 0), zoom=5, proportion=1.0, colors=['blue', 'red', 'yellow', 'orange'], m=None, width='600px', height='400px'): if m is None: m = Map(center=center, zoom=zoom) m.layout.width = width m.layout.height = height if proportion < 1.0: n_samples = int(x.shape[0] * proportion) x, y = shuffle(x, y) x = x[:n_samples] y = y[:n_samples] for sample_x, sample_y in zip(x.tolist(), y.tolist()): circle = Circle() circle.location = sample_x circle.radius = 100 circle.color = colors[sample_y] circle.fill_color = colors[sample_y] m.add_layer(circle) return m
def __init__(self, n_days_old_satimg=1): t = datetime.datetime.now() - datetime.timedelta(days=n_days_old_satimg) t_str = t.strftime("%Y-%m-%d") self.m = Map( layers=[ basemap_to_tiles(basemaps.NASAGIBS.ModisTerraTrueColorCR, t_str), ], center=(52.204793, 360.121558), zoom=2, ) self.domain_coords = [] self.polygon = None self.marker_locs = {} self.m.on_interaction(self._handle_map_click) button_reset = Button(description="reset") button_reset.on_click(self._clear_domain) button_save = Button(description="save domain") button_save.on_click(self._save_domain) self.name_textfield = Text(value="domain_name", width=10) self.m.add_control(WidgetControl(widget=button_save, position="bottomright")) self.m.add_control(WidgetControl(widget=button_reset, position="bottomright")) self.m.add_control( WidgetControl(widget=self.name_textfield, position="bottomright") )
def __init__(self, session=None): self.session = session self.use_grid = self.settings["enabled_grid"] # generate map grid polygon layers self.grid_layers = LayerGroup() self.grid_dict = {} for feat in above_grid["features"]: level = feat["properties"]["grid_level"] if level == self.use_grid: Cell_object = Cell(feat) #Cell_object.layer.on_click() grid_id = Cell_object.id self.grid_dict[grid_id] = Cell_object self.grid_layers.add_layer(self.grid_dict[grid_id].layer) # make an attribute that will hold selected layer self.selected_layer = LayerGroup() self.map = Map(layers=( esri, self.grid_layers, self.selected_layer, ), center=(65, -100), zoom=3, width="auto", height="auto", scroll_wheel_zoom=True) # map draw controls self.draw_control = DrawControl() self.draw_control.polyline = {} self.draw_control.circle = {} self.draw_control.circlemarker = {} self.draw_control.remove = False self.draw_control.edit = False self.draw_control.polygon = {**draw_style} self.draw_control.rectangle = {**draw_style} self.draw_control.on_draw(self.update_selected_cells) self.map.add_control(self.draw_control) # output display self.output = Output(layout=Layout(width="auto", height="auto")) # make the widget layout self.ui = VBox( [ #header, #HBox([instruct, geojson_text]), self.map, self.output ], layout=Layout(width="auto")) # display ui display(self.ui)
def show_map(selected_stats, year): control = WidgetControl(widget=districtbox, position='topright', min_width = 250, max_width=500) # load selected stats into choro_data_all choro_data_all, unit = choro_data_complete[selected_stats], units[selected_stats] # for geo plot extract chosen year and assign to choro_data choro_data = choro_data_all[choro_data_all['year']==year] choro_data = dict(choro_data.drop(columns=['year', 'name']).to_dict('split')['data']) # initialize bar chart with Frankfurt vs Offenbach update_figure('06412', selected_stats, choro_data_all, year) update_figure('06413', selected_stats, choro_data_all, year) # initialize districtbox loading_name, loading_values = id_to_name['06413'], choro_data['06413'] districtbox.value = f'<center><p><b>{loading_name}</b>:</p> {loading_values:g} {unit} {norm_unit}</center>' # set y-axis label fig.update_layout(yaxis_title=f'{stat_dict[selected_stats]} [{unit} {norm_unit}]', yaxis={'range':[0,max(choro_data_all[selected_stats])]}) # define chropleth layer for basic geo plotting layer = Choropleth(geo_data=geo_data,choro_data=choro_data,colormap=cm, style={'fillOpacity': 0.65, 'dashArray': '0, 0', 'weight':1}) # define GeoJSON layer for click and hover event interactions geo_json = GeoJSON(data=geo_data, style={'opacity': 0, 'dashArray': '9', 'fillOpacity': .0, 'weight': 1}, hover_style={'color': 'blue', 'dashArray': '0', 'fillOpacity': 0.7}) # on hover, the districtbox is updated to show properties of the hovered district def update_districtbox(feature, **kwargs): feature['value'] = choro_data[feature['id']] districtbox.value = f'<center><p><b>{id_to_name[feature["id"]]}</b>:</p> {feature["value"]:g} {unit} {norm_unit}</center>' # this function is called upon a click events and triggers figure update with the arguments passed from the map def update_fig_on_click(feature, **kwags): update_figure(feature['id'], selected_stats, choro_data_all, year) geo_json.on_hover(update_districtbox) geo_json.on_click(update_fig_on_click) # add layers and controls; set layout parameters m = Map(basemap=basemaps.OpenStreetMap.Mapnik, center=(50.5,9), zoom=8) m.add_layer(layer) m.add_layer(geo_json) m.add_control(control) m.layout.width = '40%' m.layout.height = '700px' # custom made legend using min/max normalization min_value, max_value = min(choro_data.values()), max(choro_data.values()) legend = LegendControl( {f"{min_value:g} {unit} {norm_unit}": cm(0), #hier f"{min_value+0.5*(max_value-min_value):g} {unit} {norm_unit}": cm(.5), f"{max_value:g} {unit} {norm_unit}": cm(1)}, name= f"{stat_dict[selected_stats]} ({year})", position="bottomleft") m.add_control(legend) return HBox([m, fig], layout=Layout(width='85%'))
def __init__(self, bbox, zoom=8, resolution=10): center = (bbox.min_y + bbox.max_y) / 2, (bbox.min_x + bbox.max_x) / 2 self.map = Map(center=center, zoom=zoom, scroll_wheel_zoom=True) self.resolution = resolution control = DrawControl() control.rectangle = { "shapeOptions": { "fillColor": "#fabd14", "color": "#fa6814", "fillOpacity": 0.2 } } #Disable the rest of draw options control.polyline = {} control.circle = {} control.circlemarker = {} control.polygon = {} control.edit = False control.remove = False control.on_draw(self._handle_draw) self.map.add_control(control) self.bbox = None self.size = None self.rectangle = None self.add_rectangle(bbox.min_x, bbox.min_y, bbox.max_x, bbox.max_y)
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
def __init__(self, grassimg): self.grassimg = grassimg self.draw_control = None self.zoom = 15 self.center = self.centermap() self.m = Map(default_tiles=TileLayer(opacity=1.0), center=self.center, zoom=self.zoom)
def __create_map(self): # Create the "map" that will be used to display the image # the crs simple, indicates that we will use pixels to locate objects inside the map self.__map = Map(center=(50, 50), zoom=2, crs=projections.Simple, dragging=False, zoom_control=False, double_click_zoom=False, layers=[LocalTileLayer(path='white.png')], layout=dict(width='600px', height='600px')) self.__create_draw_control()
def display_map(self, map_output, hemisphere=None, extra_layers=True): """ Will render the UI using ipyleaflet and jupyter widgets """ self.map_output = map_output self.dc = DrawControl( circlemarker={}, polyline={}, rectangle={ "shapeOptions": { "fillColor": "#cc00cc", "color": "#cc00cc", "fillOpacity": 0.5 } }) if hemisphere is None: projection = widget_projections[self.projection.value] else: projection = widget_projections[hemisphere] # TODO: maybe there is a way to create the map in the constructor # and just update its properties to see if this is faster. self.map = Map(center=projection['center'], zoom=projection['zoom'], max_zoom=projection['max_zoom'], basemap=projection['base_map'], crs=projection['projection']) self.map.add_control(self.dc) self.map.add_control(self.layers_control) self.map.add_control(self.search_control) for ib_layer in flight_layers[self.projection.value]: self.map.add_layer(ib_layer(self.start_date, self.end_date)) if extra_layers: for layer in custom_layers[self.projection.value]: self.map.add_layer(layer) # if self.dc.last_draw['geometry'] is not None: # self.map.add_layer(GeoJSON(name='selected geometry', data=self.dc.last_draw)) self.map.layout.height = '560px' self.out.clear_output() if map_output == 'vertical': if hasattr(self, 'sc'): self.sc.clear_output() else: self.sc = Sidecar(title='Map Widget') with self.sc: display(self.out) with self.out: display(self.map) for component in self.controls: display(component) else: with self.out: display(self.map) display(self.out)
class Grass2Leaflet(object): def __init__(self, grassimg): self.grassimg = grassimg self.draw_control = None self.zoom = 15 self.center = self.centermap() self.m = Map(default_tiles=TileLayer(opacity=1.0), center=self.center, zoom=self.zoom) def centermap(self): centerlat = [] centerlon = [] for i in self.grassimg: centerlat.append(self.grassimg[i]['C'][0]) centerlon.append(self.grassimg[i]['C'][1]) center = (sum(centerlat) / float(len(centerlat)), sum(centerlon) / float(len(centerlon))) return center def imgoverlays(self): self.leafletimg = OrderedDict() for i in self.grassimg: layer = ImageOverlay(url=self.grassimg[i]['raster'], bounds=(self.grassimg[i]['LL'], self.grassimg[i]['UR'])) self.leafletimg[i] = layer def render(self, draw_control=None): self.imgoverlays() self.dc = None options = ['None'] self.m.add_layer(self.leafletimg[list(self.grassimg.keys())[-1]]) if len(self.grassimg) >= 2: self.maplist = widgets.Dropdown( options=options + list(self.grassimg.keys()), value=list(self.grassimg.keys())[-1], description='Select Layer:', ) self.maplist.observe(self.on_value_change, names='value') display(self.maplist) if draw_control: self.dc = DrawControl() self.dc.on_draw(handle_draw) self.m.add_control(self.dc) display(self.m) return {'map': self.m, 'drawer': self.dc} def on_value_change(self, layername): self.m.clear_layers() self.m.add_layer(TileLayer(opacity=1.0)) if self.maplist.value != 'None': self.m.add_layer(self.leafletimg[layername['new']]) def main(self): self.imgoverlays() self.render()
def __init__(self, bounds: tuple): self.layer = None self._leaflet_map = Map(layers=(basemap_to_tiles( basemaps.OpenStreetMap.BlackAndWhite), ), name="Leaflet Map", center=center(bounds), zoom=12, scroll_wheel_zoom=True) self._leaflet_map.add_control(FullScreenControl())
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 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)
def __init__(self, description: str = "Basemap", position: str = "topright", a_map: Map = None): options = list(yield_basemap_dicts()) options = [opt["name"] for opt in options] current_basemap_name = [ l for l in a_map.layers if type(l) == TileLayer ][0].name start_value = current_basemap_name if current_basemap_name in options else options[ 0] dropdown = Dropdown(description=description, options=options, value=start_value, layout=Layout(width="250px")) close_btn = Button( icon="times", button_style="info", tooltip="Close the basemap widget", layout=Layout(width="32px"), ) self.widget = HBox([dropdown, close_btn]) def switch(basemap_name): if len(a_map.layers) == 1: a_map.layers = tuple([TileLayer(**get_basemap(basemap_name))]) else: old_basemap = [ l for l in a_map.layers if type(l) == TileLayer ][0] a_map.substitute_layer(old_basemap, TileLayer(**get_basemap(basemap_name))) def on_click(change): basemap_name = change["new"] switch(basemap_name) dropdown.observe(on_click, "value") def close_click(change): if a_map.basemap_ctrl is not None and a_map.basemap_ctrl in a_map.controls: a_map.remove_control(a_map.basemap_ctrl) self.widget.close() close_btn.on_click(close_click) self.widget_control = WidgetControl(widget=self.widget, position="topright") a_map.add_control(self.widget_control) a_map.basemap_ctrl = self.widget_control switch(dropdown.value)
def render(self): self.map = Map(center=self.projections[self.h.value]['center'], zoom=1, basemap=self.projections[self.h.value]['base_map'], crs=self.projections[self.h.value]['projection']) self.map.add_control(self.dc) self.map.layout.height = '600px' for component in self.components: display(component) display(self.map)
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
def map_shapefile(gdf, colormap=mpl.cm.YlOrRd, weight=2, default_zoom=13): def n_colors(n, colormap=colormap): data = np.linspace(0.0, 1.0, n) c = [mpl.colors.rgb2hex(d[0:3]) for d in colormap(data)] return c def data_to_colors(data, colormap=colormap): c = [ mpl.colors.rgb2hex(d[0:3]) for d in colormap(mpl.colors.Normalize()(data)) ] return c def click_handler(event=None, id=None, properties=None, type=None, coordinates=None): try: datasetID = properties['time'] print(datasetID) except: pass # Convert to WGS 84 and geojson format gdf_wgs84 = gdf.to_crs(epsg=4326) data = gdf_wgs84.__geo_interface__ # For each feature in dataset, append colour values n_features = len(data['features']) colors = n_colors(n_features) for feature, color in zip(data['features'], colors): feature['properties']['style'] = { 'color': color, 'weight': weight, 'fillColor': color, 'fillOpacity': 1.0 } # Get centroid to focus map on lon, lat = gdf_wgs84.unary_union.centroid.coords.xy # Plot map and add geojson layers m = Map(center=(lat[0], lon[0]), zoom=default_zoom, basemap=basemaps.Esri.WorldImagery, layout=dict(width='800px', height='600px')) feature_layer = GeoJSON(data=data) feature_layer.on_click(click_handler) m.add_layer(feature_layer) return m
def display_da(da, cm): """ Description: Display a colored xarray.DataArray on a map and allow the user to select a point ----- Input: da: xarray.DataArray cm: matplotlib colormap Output: m: map to interact with dc: draw control Usage: View, interact and point a location to be used later on """ # Check inputs assert 'dataarray.DataArray' in str( type(da)), "da must be an xarray.DataArray" # convert DataArray to png64 imgurl = da_to_png64(da, cm) # Display latitude = (da.latitude.values.min(), da.latitude.values.max()) longitude = (da.longitude.values.min(), da.longitude.values.max()) margin = -0.5 zoom_bias = 0 lat_zoom_level = _degree_to_zoom_level(margin=margin, * latitude) + zoom_bias lon_zoom_level = _degree_to_zoom_level(margin=margin, * longitude) + zoom_bias zoom = min(lat_zoom_level, lon_zoom_level) - 1 center = [np.mean(latitude), np.mean(longitude)] m = Map(center=center, zoom=zoom) # http://leaflet-extras.github.io/leaflet-providers/preview/ esri = basemap_to_tiles(basemaps.Esri.WorldImagery) m.add_layer(esri) io = ImageOverlay(name='DataArray', url=imgurl, bounds=[(latitude[0], longitude[0]), (latitude[1], longitude[1])]) m.add_layer(io) dc = DrawControl(circlemarker={'color': 'yellow'}, polygon={}, polyline={}) m.add_control(dc) m.add_control(LayersControl()) return m, dc, io
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 __init__(self, lat, lon, zoom=10): self.lat_center = lat self.lon_center = lon try: self.zoom = zoom except: pass self.map = Map(center=[self.lat_center, self.lon_center], zoom=self.zoom, width='100%', heigth=6000)
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 SelectMap(): """Create a Map object using ipyleaflet module. Returns: Map,DrawControl (ipyleaflet objects) """ m = Map(basemap=basemaps.Esri.WorldStreetMap, center=(40.853294, 14.305573), zoom=4, dragging=True, scroll_wheel_zoom=True, world_copy_jump=False) draw_control = DrawControl() draw_control.rectangle = { "shapeOptions": { "fillColor": "#fca45d", "color": "#fca45d", "fillOpacity": 0.3 } } # only rectangle selection is provided draw_control.circle = {} draw_control.polygon = {} draw_control.polyline = {} draw_control.circlemarker = {} return m, draw_control
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)