Weather mapΒΆ

This notebook shows an example of use of the AppLayout template, which is documented in Layout Templates notebook. You can check that notebook for further explanation.

This notebook depends on extra packages:

  • bqplot - widget-based plotting library,

  • ipyleaflet - cartography widget based on leaflet.js

If you also would like to see a color weather map, you will need to obtain an API key from OpenWeahterMap.

[1]:
from ipyleaflet import Map, basemaps, basemap_to_tiles, Heatmap, TileLayer
from ipywidgets import AppLayout
from ipywidgets import HTML, Layout, Dropdown, Output, Textarea, VBox, Label
import bqplot as bq
import numpy as np
from pandas import date_range
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-19dc9c0d4bb1> in <module>
----> 1 from ipyleaflet import Map, basemaps, basemap_to_tiles, Heatmap, TileLayer
      2 from ipywidgets import AppLayout
      3 from ipywidgets import HTML, Layout, Dropdown, Output, Textarea, VBox, Label
      4 import bqplot as bq
      5 import numpy as np

ModuleNotFoundError: No module named 'ipyleaflet'

To see map overlays obtain your API key free of charge from OpenWeatherMap and paste it below.

[2]:
OWM_API_KEY = "PASTE_YOUR_OWM_API_KEY_HERE" #openweathermap API key
[3]:
m = Map(center=(52, 10), zoom=5, basemap=basemaps.Hydda.Full)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-1a48879f5af6> in <module>
----> 1 m = Map(center=(52, 10), zoom=5, basemap=basemaps.Hydda.Full)

NameError: name 'Map' is not defined
[4]:
maps = {'Hydda' : basemaps.Hydda.Full,
        'Esri' : basemaps.Esri.DeLorme}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-12abbaade7ba> in <module>
----> 1 maps = {'Hydda' : basemaps.Hydda.Full,
      2         'Esri' : basemaps.Esri.DeLorme}

NameError: name 'basemaps' is not defined
[5]:
header = HTML("<h1>Fictional World Weather</h1>", layout=Layout(height='auto'))
header.style.text_align='center'
basemap_selector = Dropdown( options = list(maps.keys()),
                            layout=Layout(width='auto'))

heatmap_selector = Dropdown(options=('Temperature', 'Precipitation'),
                            layout=Layout(width='auto'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-a013a24fcdf0> in <module>
----> 1 header = HTML("<h1>Fictional World Weather</h1>", layout=Layout(height='auto'))
      2 header.style.text_align='center'
      3 basemap_selector = Dropdown( options = list(maps.keys()),
      4                             layout=Layout(width='auto'))
      5

NameError: name 'HTML' is not defined
[6]:
basemap_selector.value = 'Hydda'
m.layout.height='600px'
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-deacfe550c26> in <module>
----> 1 basemap_selector.value = 'Hydda'
      2 m.layout.height='600px'

NameError: name 'basemap_selector' is not defined
[7]:
security_1 = np.cumsum(np.random.randn(150)) + 100.

dates = date_range(start='01-01-2007', periods=150)

dt_x = bq.DateScale()
sc_y = bq.LinearScale()

time_series = bq.Lines(x=dates, y=security_1, scales={'x': dt_x, 'y': sc_y})
ax_x = bq.Axis(scale=dt_x)
ax_y = bq.Axis(scale=sc_y, orientation='vertical')

fig = bq.Figure(marks=[time_series], axes=[ax_x, ax_y],
                fig_margin=dict(top=0, bottom=80, left=30, right=20))

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-5bb2e06fa3db> in <module>
----> 1 security_1 = np.cumsum(np.random.randn(150)) + 100.
      2
      3 dates = date_range(start='01-01-2007', periods=150)
      4
      5 dt_x = bq.DateScale()

NameError: name 'np' is not defined
[8]:
m.layout.width='auto'
m.layout.height='auto'
fig.layout.width='auto'
fig.layout.height='auto'
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-6e2df7b01791> in <module>
----> 1 m.layout.width='auto'
      2 m.layout.height='auto'
      3 fig.layout.width='auto'
      4 fig.layout.height='auto'

NameError: name 'm' is not defined
[9]:
out = HTML(
    value='',
    layout=Layout(width='auto', height='auto')
)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-edb54d46d1a4> in <module>
----> 1 out = HTML(
      2     value='',
      3     layout=Layout(width='auto', height='auto')
      4 )

NameError: name 'HTML' is not defined
[10]:
AppLayout(center=m,
          header=header,
          left_sidebar=VBox([Label("Basemap:"),
                             basemap_selector,
                             Label("Overlay:"),
                             heatmap_selector]),
          right_sidebar=fig,
          footer=out,
          pane_widths=['80px', 1, 1],
          pane_heights=['80px', 4, 1],
          height='600px',
          grid_gap="30px")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-6f9084edee9a> in <module>
----> 1 AppLayout(center=m,
      2           header=header,
      3           left_sidebar=VBox([Label("Basemap:"),
      4                              basemap_selector,
      5                              Label("Overlay:"),

NameError: name 'AppLayout' is not defined
[11]:
rows = []
[12]:
X, Y = np.mgrid[-90:90:10j, -180:180:20j]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-07a0c35837f7> in <module>
----> 1 X, Y = np.mgrid[-90:90:10j, -180:180:20j]

NameError: name 'np' is not defined
[13]:
X = X.flatten()
Y = Y.flatten()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-d97ad929cf91> in <module>
----> 1 X = X.flatten()
      2 Y = Y.flatten()

NameError: name 'X' is not defined
[14]:
temps = np.random.randn(200, 150)*0.5
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c902a15bb16e> in <module>
----> 1 temps = np.random.randn(200, 150)*0.5

NameError: name 'np' is not defined
[15]:
from datetime import datetime
[16]:
import random
[17]:
def add_log(msg):
    max_rows = 3
    rows.append(msg)
    if len(rows) > max_rows:
        rows.pop(0)
    return '<h4>Activity log</h4><ul>{}</ul>'.format('<li>'.join([''] + rows))

def generate_temp_series(x, y):
    if heatmap_selector.value == 'Precipitation':
        temp = np.cumsum(np.random.randn(150)) + 100.
    elif heatmap_selector.value == 'Temperature':
        dist = np.sqrt((X - x)**2 + (Y-y)**2) / 100
        dist = dist.max() - dist
        dist[dist > np.percentile(dist, 5)] = 0
        temp = np.cumsum(np.dot(dist, temps)+0.05) + 20 - np.abs(x) / 2
    time_series.y = temp

def handle_interaction(**kwargs):
    if kwargs['type'] == 'click':
        generate_temp_series(*kwargs['coordinates'])
        msg = '%s Selected coordinates: %s, Temp: %d C Precipitation: %d mm\n' % (
            datetime.now(), kwargs['coordinates'], random.randint(-20, 20), random.randint(0, 100))
        out.value = add_log(msg)

m.on_interaction(handle_interaction)

def on_map_selected(change):
    m.layers = [basemap_to_tiles(maps[basemap_selector.value]), weather_maps[heatmap_selector.value]]

basemap_selector.observe(on_map_selected, names='value')
heatmap_selector.observe(on_map_selected, names='value')

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-1bc2ae4fae9a> in <module>
     23         out.value = add_log(msg)
     24
---> 25 m.on_interaction(handle_interaction)
     26
     27 def on_map_selected(change):

NameError: name 'm' is not defined
[18]:
temp = TileLayer(min_zoom=1, max_zoom=18, url='https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid='+OWM_API_KEY, name='owm', attribute='me')
precipitation = TileLayer(min_zoom=1, max_zoom=18, url='https://tile.openweathermap.org/map/precipitation_new/{z}/{x}/{y}.png?appid='+OWM_API_KEY, name='owm', attribute='me')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-5a7845731099> in <module>
----> 1 temp = TileLayer(min_zoom=1, max_zoom=18, url='https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid='+OWM_API_KEY, name='owm', attribute='me')
      2 precipitation = TileLayer(min_zoom=1, max_zoom=18, url='https://tile.openweathermap.org/map/precipitation_new/{z}/{x}/{y}.png?appid='+OWM_API_KEY, name='owm', attribute='me')

NameError: name 'TileLayer' is not defined
[19]:
weather_maps = {'Temperature' : temp,
                'Precipitation' : precipitation}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-3bfd213afb70> in <module>
----> 1 weather_maps = {'Temperature' : temp,
      2                 'Precipitation' : precipitation}

NameError: name 'temp' is not defined
[20]:
m.add_layer(weather_maps[heatmap_selector.value])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-8e1ca5899346> in <module>
----> 1 m.add_layer(weather_maps[heatmap_selector.value])

NameError: name 'm' is not defined
[ ]: