Some Bits: Nelson's log

8 posts about leaflet

Hawaiian Homelands revisited

At Kiwi Foo I met someone who was interested in the Hawaiian Homelands, so I revised the map I made and got it working again. Refreshed the data too, the state published a new file from the 2015 census that includes population information. The new slippy map is here. I also made a rough GeoJSON view using geojson.io; just the converted state data, no ahupuaʻa or interpretive mapping.

From a technical point of view the main thing I had to do was convert the map from using Mapzen (RIP) to vanilla Leaflet. Not too hard since Mapzen’s Javascript was based on Leaflet, but I’m lacking a good replacement for their geocoder search. I replaced their map tiles with Carto’s Positron. Here’s a good list of free map tiles that I found that on. I probably should have just done the whole thing again in Mapbox GL JS but that was more work than just porting from Mapzen to Leaflet. Also Mapbox isn’t a free service.

I didn’t do more on this project before because I don’t understand the history and importance of the Hawaiian Homelands enough to really do it right. But the guy I met has a lot more knowledge and knows some folks, we may work together to do more. A good static map for Wikipedia seems valuable, something simple like the state’s preview. I’d love to get more specific data about every individual parcel, there’s only 75 and they must have interesting histories. Maybe turn that research into a magazine article or something.

 

Leaflet heatmap options considered

I mentioned wanting a heatmap for some geographic data. Leaflet has a variety of heatmap plugins, I spent a couple of hours looking at them.

First, a word about heatmaps. A true heatmap has a feature where if you keep adding points (“heat”) to a spot, that heat diffuses and spreads out. In theory you could cover the whole world in hot red just adding to a single lat/lon because the heat diffuses (unless you have cooling/decay enabled). I want this feature. Calculating diffusion like this is complicated and slow. So most “heatmaps” cheat and instead of running a diffusion algorithm just draw blurry transparent dots. When they overlap it looks a lot like a heatmap, but you never get the full diffusion. It’s a reasonable compromise for a lot of applications (and way faster, particularly since it’s GPU-friendly) but it’s a compromise I’m hoping to avoid. See also this technical discussion.

Another key thing is how map zooming is handled. The heat blobs are really rendered in terms of pixels, not meters or geographic degrees, so the heatmap picture needs to be re-rendered at every zoom level. Some of the libraries look like they just render one image and raster scale it to match the zoom. The behavior I want is visible in this demo: notice how the blobs get more detailed when you zoom in.

Anyway, here’s my quick review of the 7 plugins:

  • Leaflet.heat; first one I’ve used. Canvas based, seems to work for 20,000 points no problem. Not a true heatmap, just fuzzy circles, but it looks good. Last update a year ago.
  • heatmap.js: canvas based, I think a true heatmap. Demo doesn’t recalculate on zoom the way I want and I don’t think there’s code for doing it. The library is mostly used for rendering user attention on web pages.
  • webgl-heatmap-leaflet. I gotta think WebGL is a good idea. New code, mostly 3 months old. Unfortunately it doesn’t seem to have the zooming behavior I want. There’s some scaling code (units and size option) but that seems to be about projecting circles of a consistent size at different latitudes.
  • Leaflet-solr-heatmap, see examples here. It’s pretty impressive being able to handle 10M points but the grid display isn’t what I’m looking for.
  • leaflet-div-heatmap is clever for using CSS and divs. No live demo I could find though, and no commits in 4 years, so I stopped looking.
  • MaskCanvas: not a heatmap, more of a “reveal the map” display. It’s neat though! Last real update was 2 years ago.
  • HeatCanvas: true heatmap, a bit too oriented towards static images. Not sure if it works well in zooming. Last real update was 4 years ago, I didn’t look further.

In summary: Leaflet.heat is the one I want. It’s the only library that recalculates on zoom. The downside is it’s not a true heatmap. I think that actually matters for my application (I expect a lot of dwell time in one place) but it’s a compromise I can accept.

Worth keeping an eye on mourner’s WebGL work for mapbox.js too; I’d rather just use vanilla Leaflet though. But his demo looks great.

IPython notebooks + geodata

IPython notebooks (ie: Jupyter) seem like an important innovation for me. A really nice web-native REPL for exploratory programming, including decent visualization of data. Plot data in particular, graphing with matplotlib. It’s quite capable, I think approaching what people do with R.

So I’ve been asking around about adding geodata capability to Jupyter. My first thought was a visualizer for GeoJSON, but I’ve learned now there are other approaches. I asked SeanG and he pointed me to a couple of things, which lead to some other things.

Summary: there are several geodata visualization packages that work with IPython. Some integrate with matplotlib and some are standalone geographic tools. None of them quite worked right for me after just a few minutes tinkering, but several seem worth the effort to get working.

folium is closest to what I’m looking for. It’s a Leaflet wrapper for Python with baked in support for geojson, various Stamen tilesets, etc. It seems to support inline plots in IPython notebooks but I couldn’t figure it out, there’s been some discussion that it should work. It doesn’t use matplotlib.

leafletwidget is another Leaflet-based map making tool, here’s an example notebook screenshot. It’s not packaged on PyPI and hasn’t been updated in awhile, looks like it’d take some effort to figure out how to use. But it might be a good basis for building my own thing.

mpleaflet lets you visualize matplotlib plots using Leaflet to add a geographical basemap. It looks very promising but I had some trouble using it out of the box. The key thing here is adding map capability to matplotlib, the primary charting visualization library IPython users use already. Seems good for data visualization but less map-specific.

matplotlib basemap toolkit is a more low-level tool for making maps with matplotlib. No Leaflet or otherwise fancy slippy map, it’s just helping you do map projections and draw geographic data in a single static image. Might be nice for one off visualizations!

cartopy is another non-leaflet map maker in python using matplotlib. It has support for using GoogleTiles. IPython support is not mentioned in the docs but it seems to work.

mpld3 has nothing to do with maps but is neat. It adds D3 rendering for matplotlib plots in your notebook, so you have fancy interactive javascript instead of a static image. Works great right out of the box. I want something that works like this for geodata. See also mplexporter, which seems to handle getting the data out of matplotlib.

GeoPandas is a bridge between Pandas and geographic data, including shapeley/fiona support. It uses descartes too, which is a bridge from geodata to matplotlib plots.

Leaflet GeoJSON vector tiles

Half-finished notes, but I don’t want to lose them.

Leaflet doesn’t have a stock plugin for GeoJSON vector tiles. I believe Glen Robertson’s leaflet-tilelayer-geojson is the most complete and correct plugin, but it renders pretty slowly (several seconds for cached data). My river vector tiles tutorial includes a TileLayer.d3_geoJSON.js that renders about 10x faster, but because it uses D3 instead of Leaflet to do the GeoJSON rendering it lacks full Leaflet integration. For instance, there’s no way to bind a Leaflet popup to a LineString.

Over on the Leaflet-js mailing list I started a discussion “GeoJSON performance? River vector tile map, trying to figure out how to make Glen’s approach using Leaflet GeoJSON faster. Norbert Renner responded with some terrific experimental work that made rendering much faster, but it was sort of a one-off spike rather than a reusable improvement. Someone should spend some time with his optimizations and see if they can be ported to work in the general purpose library.

 

More TopoJSON / watershed maps

I played more with the California watershed boundary data and TopoJSON. Two nice treatments, online at least temporarily. A full-state static map in D3 with some mild interaction letting you change the depth of HUC codes used in coloring. And a zoomable map written with Leaflet that while HUC colored, emphasizes watershed boundary details over the hierarchical HUCs.

The Leaflet implementation went pretty well. The one thing that tripped me up is my watershed boundaries are stored as bunch of Geometry objects in a GeometryCollection, instead of Feature objects in a FeatureCollection. Leaflet’s GeoJSON support does nice things with FeatureCollections, letting you change the style and bind a popup for each Feature. It doesn’t seem to do that with GeometryCollections. I worked around it by just iterating through the GeometryCollection and adding each Geometry manually. But I wonder if TopoJSON should be emitting FeatureCollections instead? ogr2ogr on my source .SHP data emitted a FeatureCollection, but topojson generated a topology with an embedded GeometryCollection.

I had to regenerate the TopoJSON for the zoomable map with less simplification. 2.2 MB vs 1.4 MB, and it looks good at reasonable zoom scales. I realized too late I really should have changed the quantization from 10,000 to 100,000; but at this simplification level I can get away with it.

So that’s the result. It’s OK and a useful tool for exploring watersheds, but it’s not awesome. The file size and render times are awfully big. And the presentation is clumsy, I should do more.

Screen Shot 2013-02-19 at 6.01.27 PM Screen Shot 2013-02-19 at 6.01.45 PM

HTML5 template with D3 and Leaflet

I’m often making D3 pages, or Leaflet maps, or some fancy Javascript thing. I always start with a blank editor and then have to remember all the HTML 5 boilerplate. So here’s some boilerplate, a template for starting a D3 + Leaflet project. The browser window is filled with the map.

This validates HTML 5. I’m not confident I’m setting the viewport correctly but this looks right in Chrome, Firefox, and Mobile Safari so good enough for me. I hate that HTML has so much boilerplate associated with it. Update: Mike points out HTML 5 doesn’t require so much boilerplate; tags like head and body are now optional. I don’t know what that means for old browser compatibility though so I’ll stick with the extra words. (Useful reference.)

<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0"/>

<title>Leaflet template</title>

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
<!--[if lte IE 8]>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
<![endif]-->
<script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>

<script src="http://d3js.org/d3.v3.min.js"></script>

<style type="text/css">
html, body { height: 100% }
#map { min-height: 100%; }
body {
    margin: 0;
    font-family: Helvetica, Arial, sans-serif; font-size: 12px;
    overflow: hidden;
    background-color: #f00;
}
</style>

</head><body>

<div id="map"></div>

<script type="text/javascript">
var map = L.map('map');
map.setView([37.7504, -122.4425], 13);
var basemap = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
        attribution: '<a href="http://content.stamen.com/dotspotting_toner_cartography_available_for_download">Stamen Toner</a>, <a href="http://www.openstreetmap.org/">OpenStreetMap</a>, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        maxZoom: 17
});
basemap.addTo(map);
</script>
</body></html>

Leaflet thoughts

I’m liking Leaflet. It’s got all the great flexibility I love in Polymaps, quickly compositing various layers of raster and vector data into one fancy map. But unlike Polymaps it runs well on iOS devices. And it’s got an active community; Polymaps feels like a dead end.

A few things are missing:

There’s no way to specify the z-ordering of layers, it’s all just in whatever order they are. The developers have said they’re working on this. (Z ordering basically doesn’t exist in SVG, it’s all document order. That’s dumb.)

Scaling transitions aren’t beautiful. Leaflet animates the raster layer but hides my vectors and then has them blink back into place. Bah.

Screenshot of work in progress. Lots going on here... Purple is steps. Orange squiggles are my walks. Faded = older walks. Redder = longer walks. There’s some interaction, too. Click on a track to highlight it and get a popup showing length and age.

Quick Leaflet with GeoJSON demo

I’m exploring Leaflet as an alternative to Polymaps, mostly because Leaflet has some momentum and is faster to render on iOS. here’s a quick demo of drawing a raster map with a GeoJSON overlay.

var map = new L.Map('map');
var rasterLayer = new L.TileLayer('http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg', {
    attribution: 'Stamen Terrain',
    maxZoom: 18
});
var view = new L.LatLng(37.75, -122.43); // geographical point (longitude and latitude)
var trackLayer = new L.GeoJSON(track);
map.setView(view, 14);
map.addLayer(rasterLayer);
map.addLayer(trackLayer);

“track” was preloaded as a JSONP script. ogr2ogr barfs on converting my GPX files from Runkeeper directly to GeoJSON, so I exported them out of PostGIS instead with

select ST_AsGeoJSON(wkb_geometry)
from tracks
where name like '%4/21/12%'

Leaflet uses SVG for the GeoJSON layer. Pretty simple structure, svg > g > path, I think one per GPS track.

With just a bit more work it was easy to load 65 walking tracks via Ajax (165k data total) and plot them all in a browser. Performance is pretty good on iOS; the main thing I don’t like is the way the GeoJSON layers disappear during a resize.