“Marionette Maps” is an on-going series on building a loosely coupled, configuration driven map viewer using Marionette.js. Read Part 1, Part 2, Part 3, Part 4.
Sharable Maps
Maps are great on their own, but to be really useful, we need to be able to share them with others. For our example application, sharing needs to mean more than “here’s the url – find the XYZ fire and check out what’s happening”. Instead, we want to allow users to share the app AND the current viewing context the same way they share anything else – copy the url, and email/tweet/facebook/pinterest away.
This means we need a way to store “context” in the url, and this is where the Backbone Router comes into play. By using the router, we can add linkable, bookmarkable, sharable URLs into our app with very little work. To keep things simple here, we are just going to store the map center, and the current zoom level in the url.
In keeping with our established pattern of putting code into modules, I created the RouterModule.js file, and set it up the same way. Additionally, I’m using events to communicate between the EsriMapModule and the Router so we keep things separated.
The core logic goes like this:
- When the map extent changes, and event is raised telling the router to update the page url. The lat/long of the center of the map as well as the current zoom level are passed along.
- The router is notified of the event, and it creates the appropriate url “fragment” and updates the url on the page, and also updates the history in the browser.
- Additionally, when the app loads, it parses out the url fragment, and the router raises an event, asking the map to set the center and zoom level.
The router code itself is very simple as shown in this gist:
The important stuff is really setting up the routes in the routes hash, and then the handler, called centerAndZoom, which really just raises and event for the map to deal with.
Over on the EsriMapModule, we had to make a few additions. First, we hooked an event handler to the onZoomEnd and onPanEnd events. In both cases, we just get the current center of the map, and the zoom level, then raise the event and let the Router take care of things for us.
Now, the obvious thing is that we are not sharing the complete state of our application – suppose I’m looking at a fire from 2010, how would we handle that? The easiest option is to add some additional optional parameters to our route, and we will look at doing that after we get the fire points display wired up in the next post.
Code
The code for this post is tagged v0.0.5 on github
Latest version of the app can be seen at http://dbouwman.github.com/geomacmapper