# From https://ipyleaflet.readthedocs.io/en/latest/api_reference/choropleth.htmldefload_data(url,nom_fichier,type_fichier):r=requests.get(fileurl)withopen(nom_fichier,'w')asf:f.write(r.content.decode("utf-8"))withopen(nom_fichier,'r')asf:returntype_fichier(f)unemployment=load_data('https://raw.githubusercontent.com/jupyter-widgets/ipyleaflet/master/examples/US_Unemployment_Oct2012.csv','US_Unemployment_Oct2012.csv',pd.read_csv)unemployment=dict(zip(unemployment['State'].tolist(),unemployment['Unemployment'].tolist()))

# Nopw that we have the data ready & loaded, we can start building a layered map step by step# First, we start with a simple basemapbasemap=basemaps.Esri.WorldTopoMapdefault_layer=basemap_to_tiles(basemap)default_layer.name='Basiskaart'# Overview of more basemaps: https://leaflet-extras.github.io/leaflet-providers/preview/ + # https://github.com/jupyter-widgets/ipyleaflet/blob/master/ipyleaflet/basemaps.py# Set initial center and zoom level of basemapcenter=(52.088889,5.33)#Utrecht cityzoom=8# Set layoutmap_layout={'width':'900px','height':'1000px','border':'1px solid black','padding':'1px','margin':'0 auto 0 auto'}# Output the map to screen, embedded in notebook#m = Map(layers=(default_layer,), center=center, zoom=zoom, layout=map_layout)#m

# Create next layers: (only CREATE layer, we don't yet ADD it to the map, as we first want to group it with other layers)# Dark background, 'night theme'dark_layer=basemap_to_tiles(basemaps.CartoDB.DarkMatter)#m.add_layer(dark_layer) # If you uncomment this, the dark layer will be added to the map in de cell above# Make heatmap of libraries - #https://ipyleaflet.readthedocs.io/en/latest/api_reference/heatmap.htmlsimple_heatmap=Heatmap(locations=lib_coor_list,# list of library coordinates, from cell abovemax=10,min_opacity=0.5,max_zoom=19,#If max_zoom value is small (6 o so..) the heatmap layer becomes untoggleable (can't be switched on/off, see cells below)radius=7.0,blur=3.0,gradient={0.4:"blue",0.6:"cyan",0.7:"lime",0.8:"yellow",1.0:"red"}#name = 'Heatmap openbare bibliotheken')#m.add_layer(simple_heatmap) # If you uncomment this, the heatmap layer will be added to the map in de cell above

# Next we want to add a popup for every library in the heatmap, containing address info of the library# As we can't directly add popus to a heatmap, we first need to make a circular marker for every library, # to which we then connect a popup. We then group together all the circles+popups into one single layer.circlelist=[]forresultinresults["results"]["bindings"]:#============================Popup contents================================libname=result['itemLabel']['value']#library name(label) in Dutch#https://wiki.python.org/moin/KeyError# Image in the left pane of the popupimagedefault='https://www.schoolenveiligheid.nl/wp-content/uploads/sites/2/2015/04/logo-bibliotheek1.jpg'img=result.get('image',imagedefault)ifisinstance(img,dict):popup_image="<img src='"+img['value']+"' width='100px'/>"ifisinstance(img,str):popup_image="<img src='"+img+"' width='100px'/>"websitedefault=''web=result.get('website',websitedefault)ifweb!=websitedefault:ifisinstance(web,dict):website="<a href='"+web['value']+"' target='_blank'>Website</a>"#target='_blank' does not yet workifisinstance(web,str):website="<a href='"+web+"' target='_blank'>Website</a>"else:website=''addressdefault=''addr=result.get('address',addressdefault)ifisinstance(addr,dict):address=addr['value']ifisinstance(addr,str):address=addr# From : 'Afhaalpunt Poortugaal, Dorpsstraat 34, 3171 EH Poortugaal, Nederland' # To: # Dorpsstraat 34 (street)# 3171 EH Poortugaal (postal_town)ifaddress!=addressdefault:street=address.split(',')[:-1][-2]+"<br/>"postal_town=address.split(',')[:-1][-1]+"<br/>"else:address=addressdefaultphonedefault=''phn=result.get('phone',phonedefault)ifisinstance(phn,dict):phone=phn['value'].replace('-','').replace('+31','0')+"<br/>"# From +31-78-620-5500 --> 0786205500 ifisinstance(phn,str):phone=phn.replace('-','').replace('+31','0')+"<br/>"emaildefault=''eml=result.get('email',emaildefault)ifisinstance(eml,dict):email=eml['value'][7:]+"<br/>"#strip the "mailto:" partifisinstance(eml,str):email=eml[7:]+"<br/>"#============================================================# This template determines the text layout in the popup. # With the external css you can tweak the styling of the textlib_popup_template=""" <!DOCTYPE html> <html> <head> <link rel='stylesheet' type='text/css' href='popupstyle.css'> </head> <body> <h4>{xlibname}</h4> <p>{xstreet}{xpostal_town}{xphone}{xemail}{xwebsite} </p> </body> </html> """rendered_template=lib_popup_template.format(xlibname=libname,xstreet=street,xpostal_town=postal_town,xphone=phone,xemail=email,xwebsite=website)message=HTML()message.value=rendered_templatemessage.description=popup_image#============================================================coor=result['coordinates']['value']#coordinatescircle=Circle(location=coor,radius=12,color="red",fill_color="red",opacity=0.005)#0.005 = hardly visiblecirclelist.append(circle)circle.popup=message# Bind popup to circle# Create 1 layer (group) from all the circles + popupslib_circles_popups=LayerGroup(layers=circlelist,name='Bibliotheekinformatie (klik op bolletje)')# Group 3 layers (simple_heatmap, dark map style and circles-layer) into 1 layerheatmap_full=LayerGroup(layers=(simple_heatmap,dark_layer,lib_circles_popups),name='Heatmap openbare bibliotheken')#m.add_layer(heatmap_full)

# We want to make a layer displaying the boundaries of all municipalities in The Netherlands that have public libraries#, using gepshapes# To make this layer, we first need to requets GeoJson geoshapes (boundaries) from Wikidata Q-values. See# https://phabricator.wikimedia.org/T138868# https://maps.wikimedia.org/geoshape?getgeojson=1&ids=Q701,Q702 or# https://maps.wikimedia.org/geoshape?getgeojson=1&query=<SPARQL> # To be precise: request boundaries (geoshapes) of Dutch municipalities that have (one or more) public libraries# We do this via P131, 'located in the administrative territorial entity' = municipality where the library is locatedlocalgeojsonfile='nl_munis_with_public_libs.json'#remove this (cache) file from the server to generate a fresh/new versionifnotos.path.exists(localgeojsonfile):nl_muni_url="https://maps.wikimedia.org/geoshape?getgeojson=1&query=SELECT%20DISTINCT%20%3Fid%20WHERE%20{%0A%20%20%20%20%20%20%3Fitem%20p%3AP31%2Fps%3AP31%20wd%3AQ28564%2Cwd%3AQ11396180%3Bwdt%3AP17%20wd%3AQ55.%0A%20%20%20%20%20%20%3Fitem%20wdt%3AP131%20%3Fid.%0A%20%20%20%20%20%20%3Fid%20p%3AP31%20[ps%3AP31%20%3FidIsA].%0A%20%20%20%20%20%20VALUES%20%3FidIsA%20{wd%3AQ2039348}.%20%23filter%20only%20the%20value%20%27municipality%20of%20the%20Netherlands%27%20Q2039348%20%0A%20%20%20%20}%20"r=requests.get(nl_muni_url)withopen(localgeojsonfile,'w')asf:f.write(r.content.decode("utf-8"))withopen(localgeojsonfile,'r')asf:muni_geoshapes=json.load(f)#print(muni_geoshapes)

# We can now combine the 'muni_geoshapes' and the 'lib_density_dict' data to make a Colorpleth # to show municipal library density (per 10.000 inhabitants) on a map.# https://ipyleaflet.readthedocs.io/en/latest/api_reference/choropleth.htmldensity_style={'color':'red','opacity':1,'weight':1,'dashArray':'2','fillOpacity':0.2}libdensitylayer=Choropleth(geo_data=muni_geoshapes,#geojson dict "id":"key" - eg. "id":"Q745038" (Waalwijk)choro_data=lib_density_dict,#simple dict of "key":float #e.g. "Q745038":0.6379992344009187189 --> generated from SPARQL query in the cell abovecolormap=linear.RdYlGn_11,#https://jiffyclub.github.io/palettable/colorbrewer/sequential/#ylgnbu_3style=density_style,#value_min =0.0,#value_max = 3.0,hover_style={'fillOpacity':0.7},name='Gemeentelijke bibliotheekdichtheid, per inwoner')#m.add_layer(libdensitylayer)

# Now we want to make a layer that displays an info box containing municipal data:# 1) Name of municipality (in Dutch) - still to sparql# 2) Province the municiplaity is in # 3) No of inhabitatns (in a given year)# 4) Area in km^2 (in a given year) - still to sparql# 5) No of libraries in the municiplaity# 6) Library density - per 10.000 inhabitants# 7) Library density - per km^2 - still to calculateboxlayout=Layout(margin='0 0 0 0px',border='2px dashed white',width='auto')label=HTML()box=Box([label],layout=boxlayout)#print(layer.style.keys)defhover_handler(event=None,id=None,properties=None):label.value="<b style='color:white'>Gemeente:</b><br/><br/><br/><br/>"#label.value="<b>Gemeente:</b> "+ #properties['geounit']+\#"<br/><b>Provincie:</b> "+ #properties['subregion']+\#"<br/><b>Inwoners:</b> "+ #str('{:,}'.format(properties['pop_est']).replace(',', '.'))+\#"<br/><b>Inkomen:</b> "+ #str('{:,}'.format(properties['gdp_md_est']).replace(',', '.')) libdensitylayer.on_hover(hover_handler)#m.add_layer(muni_boundaries)widget_control=WidgetControl(widget=box,position='bottomright',min_height=115,max_height=115,min_width=250)m.add_control(widget_control)

# Define the basemapm=Map(layers=(default_layer,),center=center,zoom=zoom,layout=map_layout)# Add all layers to the basemappm.add_layer(heatmap_full)m.add_layer(libdensitylayer)#m.add_layer(muni_boundaries)# Add controlsm.add_control(LayersControl())# https://ipyleaflet.readthedocs.io/en/latest/api_reference/layers_control.htmlm.add_control(FullScreenControl())# https://ipyleaflet.readthedocs.io/en/latest/api_reference/fullscreen_control.htmlm#Display the map, embedded in notebook

# DEPRECATED# Now make a layer with above boundaries (geoshapes)# Choose styling of layermuni_style={'color':'red','opacity':1,'weight':1,'dashArray':'2','fillOpacity':0.2,'fillColor':'blue'}# 'muni_geoshapes' is GeoJson-object taken from cell abovemuni_boundaries=GeoJSON(data=muni_geoshapes,style=muni_style,name='Gemeentegrenzen',hover_style={'fillOpacity':0.3})#m.add_layer(muni_boundaries)