python4oceanographers

Turning ripples into waves

Easy interactive maps with folium

I just had my import anti-gravity feeling feeling when I found out about folium.

I have no knowledge of JavaScript nor leaflet, yet with just a few lines of python code I could generate a plot with all the HF radar station positions on an interactive map.

To start you have to download the stations positions kml file and extract the lon, lat and name data of each station.

In [2]:
from fastkml.kml import KML

def read_kml(fname='ss.kml'):
    kml = KML()
    kml.from_string(open(fname).read())
    points = dict()
    for feature in kml.features():
        for placemark in feature.features():
            if placemark.styleUrl.startswith('#hf'):
                points.update({placemark.name:
                            (placemark.geometry.y, placemark.geometry.x, )})
    return points

Then create a dictionary with data information.

In [3]:
fname = './data/ss.kml'
locations = read_kml(fname)

Now just choose a starting point and a zoom level for your map, and loop through pass the dictionary.

In [4]:
import folium


def inline_map(m, width=650, height=500):
    """Takes a folium instance and embed HTML."""
    m._build_map()
    srcdoc = m.HTML.replace('"', '"')
    embed = HTML('<iframe srcdoc="{}" '
                 'style="width: {}px; height: {}px; '
                 'border: none"></iframe>'.format(srcdoc, width, height))
    return embed


width, height = 650, 500
radars = folium.Map(location=[40, -122], zoom_start=5,
                    tiles='OpenStreetMap', width=width, height=height)

for name, location in locations.items():
    radars.simple_marker(location=location, popup=name)

inline_map(radars)
Out[4]:

That's it, now you have an interative map! (Try clicking at the stations.)

If you like this check some even more elaborate examples from the library author.

In [5]:
HTML(html)
Out[5]:

This post was written as an IPython notebook. It is available for download or as a static html.

Creative Commons License
python4oceanographers by Filipe Fernandes is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Based on a work at https://ocefpaf.github.io/.

Comments