mySociety

Home

mySociety Blog

Blog posts in the category Free Data

Mapumental’s Secret Sauce: A Map Overlay Rendering Technology You Might Find Interesting

Written by on in Free Data, Mapumental, Technical, Travel Time Maps

I am Duncan Parkes,  a developer for mySociety, a non-profit full of web geeks. One of the things we try to do well here is to take complicated data and turn it into really usable tools – tools which are attractive to people who aren’t web (or data) geeks.

For some considerable time I’ve been working on Mapumental – a project that is about turning public transport timetable data into pretty, interactive maps featuring isochrones, shapes that show people where they can live if they want to have a commute of a particular time. You can play with the new version we just launched here. That particular map shows the commuting options to where the Queen lives. Slide the slider for full effect.

There are a couple of hard problems that need solving if you want to build a service with an interactive journey times overlay like this. You need to be able to calculate a *huge* number of journeys extremely quickly, and you need to be able to make custom map layers so that it all looks nice. But what I think might be most interesting for you is the way in which the contours get rendered on top of the maps.

It all started about three years ago, when the first version of the app – co-developed with the geniuses at Stamen – used Flash/Flex to draw contours on the maps, and to let people play with them. You can still play with a couple of versions of that technology from way back in 2007, that is, unless you’re using an iPad or iPhone, which of course don’t do Flash.

Colour Cycling

What was going on inside this Flash app was as follows. We needed to show the user any one of hundreds of different combinations of journey times (5 minutes, 12 minutes, 56 minutes, etc) depending on where they set the slider. Sending each one from the server as a tiled map overlay would be dead slow. Even Google – who have chosen to send new tiles each time – end up with a service which is surprisingly slow (try choosing a different time on this map).

With some help from Stamen, we decided that the way of making it possible to show many different contours very quickly was send the client just one set of tiles, where each tile contained all the data for a variety of journey times. What does that mean? Simple: each colour in the tile represented a different number of minutes travelling on the map. So a batch of pixels that are colour X, all show places that are 15 minutes from the centre of the map.

So, in this old Flash system, when you slide the slider along, the Flash app makes some of the coloured pixels opaque, and the others transparent. It was, in short, a form of colour cycling, familiar to lovers of 8 and 16 bit computer games.

However, from about 2010 onwards, the march of iOS spelt the end of Flash. And that meant that we couldn’t launch a shiny new site based on this technology, as lovely as it was. We had to work out some approach that would use modern web standards instead.

The Death of Flash Makes Life Difficult – for a while

How do we replicate the experience of dragging a slider and seeing the map change like in the original Mapumental demo, but without Flash? One of the things that made the original Mapumental nice to use was how smooth the image changes were when you dragged the slider. Speed really matters to create that sort of organic effect that makes the demo so mesmerising.

So as we started to tackle the question “How do we make this work in a post-Flash world?”. And the first thought was “Let’s do away with those map tiles, filled with all that journey time data!”. After all – why send any tiles to a modern browser, if it can just render nice shapes on the fly?

So we had a go. Several goes. At first we tried rendering SVG circles around each public transport stop – but that was too slow, particularly when zoomed out. Then we tried rendering circles in Canvas, and whilst that was OK in sparsely populated places it sucked in the cities, where people would actually want to use it.

Eventually, we decided that as wonderful and powerful as modern web rendering techniques are, if you exclude WebGL (on the grounds that so few people have it still), all the current techniques result in pages that just hammer your browser, whilst producing an experience which isn’t up to our previous Flash-based standards. To see this in action, see the wonderful Mapnificent site, developed by the super talented Stefan Wehrmeyer. He’s a great guy and a friend of mySociety, but the Javascript circle rendering just grinds, and that’s with far, far fewer data points than we have in our system. (Sorry for potentially crashing your browser there. This is in the interest of Science.)

Back to Colour Cycling – Using Web Standards

So, we thought, why not look again at colour cycling the pixels within pre-rendered map tiles? After all, there are some examples out there, like this waterfall, all in Javascript.

So, I had a bit of a look at the waterfall. It seems to work by holding in memory a structure which has all the pixels which change and all the colours they should change to and when. This works beautifully for the waterfall picture, but only a limited number of the pixels in that image actually change colour, and the image is quite small. For a full screen web browser with a big map in, this didn’t seem promising, although I’d love to see someone try.

Then I thought: browsers have always been very good at displaying images quickly – that’s sort of vital. Perhaps we could get our tile generating server to output PNG images where, as before, the colours represent travel times, but using a palette. Then by putting this in a canvas layer in the JavaScript mapping framework Leaflet, and by changing the palette of the images on the canvas as the slider is dragged, we could get our animation.

Unfortunately, there is no way to change the palette of an image that you’ve put on the canvas. In fact, there’s no way to change the palette of an HTML img element: all you can do is assign it a new src attribute.

But this gets back to the original problem – we don’t want to download new mapping for every different position on the time slider. We definitely can’t afford to have the client downloading a new image source for every tile whenever the slider is moved, so we had to find a way to make that src at the client end and get that into the src attribute.

The Breakthrough – Data URIs and Base64 encoding

So we started trying data URIs. For those of you not familiar, these allow you to put a whole object into your HTML or CSS, encoded in Base64. They’re commonly used to prevent pages having to make extra downloads for things like tiny icons.

So I thought, “Here’s a way we can set an image src in JavaScript to something we’ve calculated, rather than something we’ve downloaded.” And this turned out to be the key insight that allows for the relatively smooth, attractive overlays you see in Mapumental today.

My new plan was that the client, having downloaded each palette-based image, would make a Base64 encoded version of it, which it could then use to build a version with the right palette and assign this as a data URI of the tile.

However Base64 encoding all these images in the JavaScript seemed like unnecessary processing to do there, so the final evolution of this technique was to do the Base64 encoding at the tile server end, and while we’re at it, not to bother sending over the parts of the image that we always replace at the client end.

So in summary, what we built does this:

  1. The server calculates the journey times and renders them to palette-based tiles.
  2. It sends these to the client, encoded in Base64, and with the initial bits up to the palette and transparency chunks removed.
  3. At the client end, we have a pre-prepared array of 255 ‘starts’ of PNGs that we combine with the later parts of the ’tiles’ from the tile server to make data URIs.
  4. When you drag the slider it combines the appropriate ‘start’ of a PNG with the bulk of the tile that has been downloaded from the server, and assigns that to the src attribute of the tile.

And that’s how the nice overlays on Mapumental work. But as so often in coding, the really interesting devil is in the detail – read on if you’re interested.

Diving into Base64 and the PNG file format – The Gnarly Bits

So – why are there 255 of these ‘starts’ of these PNGs, and what do I mean by a ‘start’ anyway?

PNG files are divided up into an 8 byte signature (the same for every PNG file) and a number of chunks, where each chunk consists of 4 bytes to tell you its length, 4 bytes of its name, some data, and 4 bytes of cyclic redundancy check. In this case, what I call a ‘start’ of a PNG is the 8 byte signature, the 25 byte of the IHDR chunk, and the PLTE (palette) and tRNS (transparency) chunks. The PLTE chunk has 12 bytes of overhead and 3 bytes per colour, and the tRNS chunk has 12 bytes of overhead and 1 byte per colour.

Base64 encoding is a way of representing binary data in text so that it can be used in places where you would normally expect text – like URIs. Without going into too much detail, it turns groups of 3 bytes of binary gumpf into 4 bytes of normal ASCII text without control characters in it, which can then be put into a URI.

Why do we have 255 colours, rather than the maximum 256 which are available in a palette? Because we need the break between the end of the tRNS chunk and the start of the IDAT chunk in the PNG file to align with a break between groups of three bytes in the Base64 encoded image. We need the length of these starts to be a multiple of 3 bytes in the original PNG format, which translates into a multiple of 4 bytes in the Base64 encoded version, so we can cut and shut the images without corruption.

Which just goes to show that even though web GIS technologies may feel like they are approaching a zenith of high level abstraction, there’s still some really gnarly work to be done to get the best out of current browsers.

Welcome, Mzalendo – Monitoring Kenya’s MPs and Parliament

Written by on in Free Data, Launches, TheyWorkForYou

When TheyWorkForYou was built by a group of volunteer activists, many years ago, it was a first-of-a-kind website. It was novel because it imported large amounts of parliamentary data into a database-driven website, and presented it clearly and simply, and didn’t supply newspaper-style partisan editorial.

These days dozens of such sites exist around the world. But today sees the launch of a rather-special new transparency site: Mzalendo, covering the Parliament of Kenya.

Mzalendo (which means ‘Patriot’ in Swahili) has been around for a few years too, as a blog and MP data website founded by volunteer activists Conrad and Ory. However, over the last few months mySociety’s team members Paul, Jessica and Edmund, plus the team at Supercool Design have been helping the original volunteers to rebuild the site from the ground up. We think that what’s launched today can stake a claim to being a true ‘second generation’ parliamentary monitoring site, for a few reasons:

  • It is entirely responsively designed, so that it works on the simplest of mobile web browsers from day one.
  • All the lessons we learned from storing political data wrongly have been baked into this site (i.e we can easily cope with people changing names, parties and jobs)
  • Every organisation, position and place in the system is now a proper object in the database. So if you want to see all the politicians who went to Nairobi University, you can.
  • There is lots of clear information on how parliament functions, what MPs and committees do, and so on.
  • It synthesizes some very complex National Taxpayer’s Association data on missing or wasted money into a really clear ‘scorecard‘, turning large sums of money into numbers of teachers.

The codebase that Mzalendo is based on is free and open source, as always. It is a complete re-write, in a different language and framework from TheyWorkForYou, and we think it represents a great starting point for other projects. Over the next year we will be talking to people interested in using the code to run such sites in their own country. If this sounds like something of interest to you, get in touch.

Meanwhile, we wish Ory and Conrad the best of luck as the site grows, and we look forward to seeing what the first users demand.

Technical look at the new FixMyStreet maps

Written by on in FixMyStreet, Free Data, Technical

This post explains how various aspects of the new FixMyStreet maps work, including how we supply our own OS StreetView tile server and how the maps work without JavaScript.

Progressive enhancement

During our work on FiksGataMi (the Norwegian version of FixMyStreet) with NUUG, we factored out the map code (for the Perlmongers among you, it’s now using Module::Pluggable to pick the required map) as FiksGataMi was going to be using OpenStreetMap, and we had plans to improve our own mapping too. Moving to OpenLayers rather than continuing to use our own slippy map JavaScript dating from 2006 was an obvious decision for FiksGataMi (and then FixMyStreet), but FixMyStreet maps have always been usable without JavaScript, utilising the ancient HTML technology of image maps to provide the same functionality, and we wanted to maintain that level of universality with OpenLayers. Thankfully, this isn’t hard to do – simply outputting the relevant tiles and pins as part of the HTML, allowing latitude/longitude/zoom to be passed as query parameters, and a bit of maths to convert image map tile clicks to the actual latitude/longitude selected. So if you’re on a slow connection, or for whatever reason don’t get the OpenLayers JavaScript in some way, the maps on FixMyStreet should still work fine. I’m not really aware of many people who use OpenLayers that do this (or indeed any JavaScript mapping API), and I hope to encourage more to do so by this example.

Zooming

We investigated many different maps, and as I wrote in my previous blog post, we decided upon a combination of OS StreetView and Bing Maps’ OS layer as the best solution for the site. The specific OpenLayers code for this (which you can see in map-bing-ol.js is not complicated (as long as you don’t leave in superfluous commas breaking the site in IE6!) – overriding the getURL function and returning appropriate tile URLs based upon the zoom level. OpenLayers 2.11 (due out soon) will make using Bing tiles even easier, with its own seamless handling of them, as opposed to my slight bodge with regard to attribution (I’m displaying all the relevant copyright statements, rather than just the one for the appropriate location and zoom level which the new OpenLayers will do for you). I also had to tweak bits of the OpenLayers map initialisation so that I could restrict the zoom levels of the reporting map, something which again I believe is made easier in 2.11.

OpenStreetMap

Having pluggable maps makes it easy to change them if necessary – and it also means that for those who wish to use it, we can provide an OpenStreetMap version of FixMyStreet. This works by noticing the hostname and overriding the map class being asked for; everything necessary to the map handling is contained within the module, so the rest of the site can just carry on without realising anything is different.

OS StreetView tile server

Things started to get a bit tricky when it came to being ready for production. In development, I had been using http://os.openstreetmap.org/ (a service hosted on OpenStreetMap’s development server) as my StreetView tile server, but I did not feel that I could use it for the live site – OpenStreetMap rightly make no reliability claims for it, it has a few rendering issues, and we would probably be having quite a bit of traffic which was not really fair to pass on to the service. I wanted my own version that I had control over, but then had a sinking feeling that I’d have to wait a month for something to process all the OS TIFF files (each one a 5km square) into millions and millions of PNG tiles. But after many diversions and dead ends, and with thanks to a variety of helpful web pages and people (Andrew Larcombe’s guide to his similar install was helpful), I came up with the following working on-demand set-up, with no pre-seeding necessary, which I’m documenting in case it might be useful to someone else.

Requests come in to our tile server at tilma.mysociety.org, in standard OSM/Google tile URL format (e.g. http://tilma.mysociety.org/sv/16/32422/21504.png. Apache passes them on to TileCache, which is set up to cache as GoogleDisk (ie. in the same format as the URLs) and to pass on queries as WMS internally to MapServer using this layer:

[sv]
type=WMS
url=path/to/mapserv.fcgi?map=os.map&
layers=streetview
tms_type=google
spherical_mercator=true

MapServer is set up with a Shapefile (generated by gdaltindex) pointing at the OS source TIFF and TFW files, meaning it can map tile requests to the relevant bits of the TIFF files quickly and return the correct tile (view MapServer’s configuration – our tileserver is so old, this is still in CVS). The OUTPUTFORMAT section at the top is to make sure the tiles returned are anti-aliased (at one point, I thought I had a choice between waiting for tiles to be prerendered anti-aliased, or going live with working but jaggedy tiles – thankfully I persevered until it all worked :) ).

Other benefits of OpenLayers

As you drag the map around, you want the pins to update – the original OpenLayers code I wrote used the Markers layer to display the pins, which has the benefit of being simple, but doesn’t fit in with the more advanced OpenLayers concepts. Once this was switched to a Vector layer, it now has access to the BBOX strategy, which just needs a URL that can take in a bounding box and return the relevant data. I created a subclass of OpenLayers.Format.JSON, so that the server can return data for the left hand text columns, as well as the relevant pins for the map itself.

Lastly, using OpenLayers made adding KML overlays for wards trivial and made those pages of the site much nicer. The code for displaying an area from MaPit is as follows:

    if ( fixmystreet.area ) {
        var area = new OpenLayers.Layer.Vector("KML", {
            strategies: [ new OpenLayers.Strategy.Fixed() ],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "/mapit/area/" + fixmystreet.area + ".kml?simplify_tolerance=0.0001",
                format: new OpenLayers.Format.KML()
            })
        });
        fixmystreet.map.addLayer(area);
        area.events.register('loadend', null, function(a,b,c) {
            var bounds = area.getDataExtent();
            if (bounds) { fixmystreet.map.zoomToExtent( bounds ); }
        });
    }

Note that also shows a new feature of MaPit – being able to ask for a simplified KML file, which will be smaller and quicker (though of course less accurate) than the full boundary.

3 Principles we are asking Speaker candidates to endorse: You can help right now

Written by on in Appeals, Commentary, Free Data, News, TheyWorkForYou

Speakers Chair (Parliamentary Copyright)
Speaker’s Chair (Parliamentary Copyright)

mySociety has today emailed (and in one case, posted) a set of 3 Principles which we believe it is important that all candidates for Speaker endorse, before the election of a new Speaker by MPs.

1. Voters have the right to know in detail about the money that is spent to support MPs and run Parliament, and in similar detail how the decisions to spend that money are settled upon.

2. Bills being considered must be published online in a much better way than they are now, as the Free Our Bills campaign has been suggesting for some time.

3. The Internet is not a threat to a renewal in our democracy, it is one of its best hopes. Parliament should appoint a senior officer with direct working experience of the power of the Internet who reports directly to the Speaker, and who will help Parliament adapt to a new era of transparency and effectiveness.

We will be posting the status of requests on the likely candidates web pages where we expect large numbers of people to see them before the vote in late June. We have also taken the unusual step of allowing possible candidates to leave a statement of up to 150 words on the principles.

(NB no candidates have actually declared at this stage, so we are starting with the BBC’s list of possibles)

Rationale

mySociety helped lead the campaign back in January to prevent the last ditch attempts to conceal MPs’ expenses. We did so not because, like the newspapers, we wanted to revel in embarrassment and scandal, but because we believe that in the Internet age, the only way for our democracy and government to thrive is if they are open and connected to the net as the rest of us expect them to be. The dramatic events seen in Parliament in recent days vindicate the view that secrecy breeds poor policies and seeds untrustworthy behaviour in the weaker willed.

Furthermore, more than a simple attitude of openness is required of the new Speaker: the public needs a genuine will to push for technological reform using the power of the Internet that will take both open-mindedness and a willing to tread on toes, especially in some parts of the unelected establishment.

Case in point: Over the last two years we have been trying to persuade Parliament to acknowledge that the way it publishes its Bills online is hopelessly inadequate for the Internet age. The campaign has faltered, despite multi partly endorsement from 140 MPs and a campaign membership of thousands. To see why, just take a look at this colourful and error-crammed internal email that we uncovered using the Freedom of Information Act, published for the first time today.

The new Speaker will have a tough job on their hands to overcome resistance of this kind. The best thing we can do is help the new Speaker, whoever they are, assume their new job with a clear mandate from the public, as well as from members.

Act!

That is why, as a final part of this call, we are asking you, our community, to write to your MP today to let them know that you expect them to vote for a candidate that has endorsed the principles above. Your voices to your own constituency MPs can resonate in a way that no blog post or newspaper article ever can. Go to it.

What does it take to get FixMyStreet to post reports directly into a council CRM? One good public servant.

Written by on in Commentary, Free Data

Recently I gave a talk at a conference where I told a group of local government officials that FixMyStreet was built not just to provide cleaner streets for their citizens, but also to force the hands of councils to procure and contract internal IT systems fit for the 21st century. In particular I pointed out that companies like Google seek to have people use their service from any site, any browser and device – they don’t just demand that everyone goes to www.google.com. And, I said, it’s only through building nice interfaces (APIs) that you can become an organisation that realises the benefits for yourself and other organisations from taking this ‘we’re happy to interoperate with anyone’ approach.

Less than three weeks later Michael Houlsby from East Hants council has single-handedly built an external facing API for their faults and problems database. So now FixMyStreet posts problems in that council direct into their database, without them first being translated into emails.

This is fantastic, especially as Michael clearly knocked it together in his spare time, and helps confirm what we’ve said before – if government builds nice interoperable APIs people like mySociety will use them to improve citizens’ experiences, whist simultaniously keeping everyone’s unnecessary workloads and expenses to a minimum. Plus it shows that if your IT supplier tells you you need to sign a new five or six figure contract to add an API to a CRM system you’ve already bought – you’re being jerked around.

Hats off to Michael – you’re a great example of a pro-active public servant using your skills to make government both better and more efficient.

Unlock your public data here

Written by on in Commentary, Free Data

The Office of Public Sector Information (snappy name, lads) has launched a simple new service where you can publicly lodge a request for some public sector data that you can’t get, but need for some reason. They’ll then act as your behind-the-scenes champions and attempt to lever it out of which ever bit of government is trying to keep hold of it for no good reason.

You can also read other people’s requests, which hopefully will help people realize how much good data there is out there, and leave comments suggesting further reasons why it might be a good idea to let it loose.

Full disclosure, this was my idea, as part of the Power of Information review, so I’m not neutral in wanting to see people get what they want through it.

Go, post!

The Free Our Bills Campaign launches

Written by on in Free Data, Launches, TheyWorkForYou

mySociety has never run a campaign before today. And we’re not sure anyone’s ever run a campaign featuring a charismatic duck-billed platypus escaping from under the closing jaws of a Parliamentary portcullis.

Platypus

Update 15.34 25/03/2008
Conservative Party leader David Cameron has just endorsed the campaign in this video.

Update 17.14 25/03/2008
Now kind words from techy Lib Dem MP Lynne Featherstone.

Update 11.38 1/04/2008
We’ve just recieved this fantastic endorsement from Nick Clegg, leader of the Liberal Democrats:

“Parliament belongs to the people. It’s time to open it up so people can find out what’s going on. mySociety has done a brilliant job in recent years in doing that – and it’s time to take this project to the next level and get information about the laws Parliament passes into the public domain.

“It takes a new MP months to figure out how the tortuous bills procedures work – so how we expect the voters to know what’s going on, I have no idea. The changes MySociety are calling for are vital so that every MP is fully accountable for the decisions they take on behalf of their constituents.

“I fully support the Free our Bills campaign, and will do all I can in Parliament to win this battle.”

Thanks Nick!

RSS feeds

Categories

Recent Posts