Monday, November 13, 2017

QGIS: Adding Bounding Box Ordinates as Shapefile Attributes

I mentioned last week, that for the purpose of zooming to a hydrology region when it's selected, we added some attributes to a CSV of metadata, which we were already loading for other UI and statistical purposes.

These attributes were called bbox_s, bbox_w, bbox_n, and bbox_e and are simply floats in WGS84 lat-long. But I thought I'd share how I generated 4 fields representing the bounding box, for these regions (and then later for a few hundred individual watersheds) quickly and easily.

To back up a bit:

  • The CSV was generated from the DBF component of that hydrology regions shapefile. Excel can load up the DBF just fine, then you use Save As and export as a CSV. Easy.
  • The shapefile has attributes of statistics which were generated by other means. The stats were miles of river, number of gauges, that sort of deal where GIS was the answer.
  • The only missing attributes now are the bounding box fields, preferably 4 floats in WGS84 lat-long.
This was done with QGIS's Field Calculator, using built-in functionality. The Field Calculator supports geometry operations including xmin and transform. So it's simple:

Take note of what SRS you are using, particularly its EPSG code.

Create a new field called bbox_s of type float. Don't forget to give it a Precision for after the decimal place! If you leave Precision at 0, the fields will still calculate but will then be truncated to whole numbers after you save.

Populate it with this formula, being sure to replace the first SRS with your dataset's own SRS:


y_min(transform($geometry, 'EPSG:3310', 'EPSG:4326'))

And there you are! You now have an attribute with the southern ordinate of the bbox. Repeat this 3 more times:

bbox_w
x_min(transform($geometry, 'EPSG:3310', 'EPSG:4326'))
 
bbox_e
x_max(transform($geometry, 'EPSG:3310', 'EPSG:4326'))
 
bbox_s
y_min(transform($geometry, 'EPSG:3310', 'EPSG:4326'))
bbox_n
y_max(transform($geometry, 'EPSG:3310', 'EPSG:4326'))

Save your edits, and you're nearly done. Load up the DBF in Excel, maybe tidy up some other fields and their formatting, and export as CSV.


Monday, November 6, 2017

More Mapbox! Using querySourceFeatures() ... or not

The project where I've been exploring Mapbox GL API continues along, and everyone is quite pleased with how it's coming along. Here's another technical posting, this time about something we needed which did not work out.

The need: One of the map layers is hydrology regions. When one is selected, it would be great to highlight it and also zoom the map to it.

Highlighting is already done and working just fine. I went with a filtering technique to swap between a choropleth of all regions, and a highlight of the one region. That's great.

Zooming though, implies that we have the bounding box coordinates handy for the selected region. Can we get these from the API, since it has the records? Answer: No.

querySourceFeatures Does Not Query


Mapbox API does provide a method that sounds promising: querySourceFeatures()  But it doesn't do what you're thinking. It queries only the vector tiles which are currently visible in the map viewport. As such, it can only query features that are already on the map and is not a search/query mechanism for your dataset.

Example code:
// specify the URL of the tileset when declaring the Source
// and ALSO its suffixed name when connecting it to a Layer
map.addSource('myplaces', {
    "type": "vector",
    "url": "mapbox://mapbox.abcde12345"
});
map.addLayer({
    "id": "places",
    "source": "myplaces",
    "source-layer": "MyPlaces-abc123",
    "type": "fill",
    "paint": {
        "fill-outline-color": "rgba(0,0,0,0)",
        "fill-color": "rgba(0,0,0,0)"
    }
});
var results = map.querySourceFeatures('myplaces', {
   sourceLayer: 'places',
   filter: [ '==', 'name', 'Montana' ],
});
console.log(results);

Limitations and expectations are:

  • The setup is a bit goofy, that you must program in both the URL of your Mapbox tileset (when creating the Source) and also the readable suffixed name of it (when adding the Layer).
  • The Source isn't actually useful unless there is also a Layer and the Layer is on the map. You can render with 0 alpha to make it invisible, but it must be on the map.
  • The query only searches within the vector tiles currently visible on the map. As you pan and zoom, you'll see that results changes even if your query does not.
The use case demonstrated by the Mapbox demos, is basically limited to querying what's under your mouse. And sadly, this does seem to be all that it's good for. querySourceFeatures() is basically the same thing as queryRenderedFeatures()except that you can specify the "click filtering" without changing the filters used for rendering.


So, What Now?


Mapbox offers a fairly new service called Datasets. When you upload your dataset, unlike Tilesets which are digested into vector tiles, this one is digested into a database and exposed as a GeoJSON structure. This can then be queried and downloaded, and there's mention of an editing and authoring environment as well.

Of course, this means uploading a second copy of these datasets just for querying purposes, which isn't so great for maintainability.

In our case, we were already loading a CSV of metadata used for constructing other UI elements and populating some statistical tables. As such, it was no problem to add to that CSV some new bbox_s, bbox_e, bbox_n, bbox_e fields to facilitate the zooming behavior. As such, I did not get an opportunity to work with Datasets this time.

Monday, October 30, 2017

Mapbox Vector Tiles + Leaflet: Bugs and Workarounds

A few weeks ago, I posted about my first experiences with Mapbox's vector tile service and the Leaflet adapter for it. A lot of things went well and the end result was quite nice, and I covered a lot of how-to items for what worked well.

But a couple of items were buggy, or needed workarounds.

Published Changes Not Saving


I mentioned this previously, but continue to replicate it. I make changes to my Style in Mapbox Studio, hit Publish, then wait patiently for the changes to show up in the browser. Sometimes it works almost instantly, sometimes I have to wait 10 minutes, and sometimes it just doesn't happen.

I hit the /styles/v1/ endpoint in my debugger, and see that they really are serving up the old colors, are not yet including my new layer, are still showing the old name for the layer, and so on.

Workaround: go into Mapbox Studio again, make some change and then undo it, and hit Publish again. Sometimes a third time is required.

Clicking and mouseover effects


The queryRenderedFeatures() method accepts a Mapbox GL Point as the query coordinates, not a L.LatLng since it's not Leaflet. The programming to convert a L.Map click event into a Mapbox GL Point and then perform a query, is as follows:
MAP.on('click', function (e) {
    const canvas   = MBOVERLAY._glMap.getCanvasContainer();
    const rect     = canvas.getBoundingClientRect();
    const glpoint  = new mapboxgl.Point(e.originalEvent.clientX - rect.left - canvas.clientLeft, e.originalEvent.clientY - rect.top - canvas.clientTop);
    const features = MBOVERLAY._glMap.queryRenderedFeatures(glpoint, { layers: INTERACTION_LAYERS });
    // now go do something with the resulting "features" list
});

Maps becoming desynchronized on a zoom change


When the L.Map changes zoom level, e.g. any time we call a fitBounds() or setView() the Mapbox GL layer would fall out of sync. The vector layer would repaint, but often not at the same center, so would be offset from the rest of the map. This would happen pretty reliably too, with only moments of testing required.

The workaround here was a bit of a hack: any time the map becomes idle after changing, have it call setCenter() on its own center after a brief timeout. This seems to trigger a repaint of the Mapbox GL layer, bringing it into sync with the rest of the map.
MAP.on('moveend', function () {
    if (! MAP.overlay._glMap) return; // map's not ready yet e.g. startup
    const center = MAP.getCenter();
    setTimeout(function () {
        MAP.overlay._glMap.setCenter(center);
    }, 250);
});
Again, an ugly hack but a lot less ugly than what it solves!

Race conditions on startup


Outside of the map is a list of hydrology regions and clicking one will trigger some behaviors on the map. Some of these behaviors include changing some filters on the Mapbox GL layer. Problem is, the Mapbox GL layer can take several seconds to initialize. If someone clicks during this time, all sorts of funky hell breaks loose in the console because MBOVERLAY._glMap is not yet defined, the Style has not yet loaded, and so on.

The workaround is not surprising: GL Map's load event, which fires after the map has first loaded and completed its first painting of the layer. Now you know that MBOVERLAY._glMap is defined and ready!
MAP.overlay = L.mapboxGL({
    accessToken: OVERLAY_ACCESSTOKEN,
    style: OVERLAY_MAPBOXURL,
    pane: 'overlayPane',
}).addTo(MAP); 

MBOVERLAY._glMap.on('load', function () {
    // addSource() and addLayer()
    // and additional UI event handlers for folks who won't wait before clicking
});

What Went Well?


Most things worked well! Those were the focus of the previous articles. :)

Hooray Mapbox, for a really excellent product which allows for filtering and re-styling in ways that would traditionally have required a WMS server.

Tuesday, October 24, 2017

Leaflet-Mapbox-GL HOWTO: Highlighting an area

My series on Mapbox GL API combined with Leaflet using leaflet-mapbox-gl.js continues.

We have been working within a function called selectRegionByName() which would switch between choropleth view and borders-only view by way of filters. Last week we added waterways and river gauges to it as well, again using filters.

This week's icing on the cake: we want to highlight the selected region as well. The black borders are showing and the choropleth is suppressed, but can we give this area a good thick orange border to make it pop?


The Easy Way: Filtering a Dedicated Layer


No surprise here: the easiest mechanism would be to add a new layer to your Style, and filter it to match the region. If we stack the highlight layer above the black outline layer and give the stroke an opacity of 1, this would effectively hide the black border of this region in favor of the orange border.

  • Go into Mapbox Studio and add a new layer called regionhighlight.
    Use the hydrology regions as the Tileset.
    Select a line type rendering, give it a good thick stroke and make it orange.
  • Set a filter on the layer to match `region == Nonexistent` so that it's not in fact matching anything at all.
  • In client-side code, follow what we did the last few postings to add a new filter for regionhighlight matching the selected region name.
The resulting additions to selectRegionByName() would look a lot like this:

// highlight overlay on: filter to match this one region
MBOVERLAY._glMap.setFilter("highlightregion", ["==", 'name', name]);

// highlight overlay off: filter to match no region ever
MBOVERLAY._glMap.setFilter("highlightregion", ["==", 'name', "Nonexistent"]);

The Harder Way: Creating a New Layer Client-Side


Back when I implemented the highlighting, I hadn't quite wrapped my head around filtering and hadn't come up with the easy method above. Instead, I used a technique described in Mapbox's documentation which uses a Tileset as a data source and adds virtual layers to the client-side map.

First off, define a Source connected to your Tileset. You will need the Tileset's Mapbox URL and the name of it as it appears in your Tilesets page.
// define a new Source
// url is the Mapbox URL of the regions Tileset
MBOVERLAY._glMap.addSource('regions', {
    "type": "vector",
    "url": "mapbox://yourusername.abcdef1234",
});

// define a line layer using the above Source
// source is the Source name you defined above
// source-layer is the Mapbox-mangled name of that Tileset
MBOVERLAY._glMap.addLayer({
    "id": "highlightregion",
    "source": "regions",
    "source-layer": "HydroRegions-abcd1234",
    "type": "line",
    "paint": {
        "line-width": 4,
        "line-color": "orange",
    },
    "filter": ["==", 'name', "Nonexistent"],
});
Now, to activate that virtual layer, you would apply a filter:
// highlight overlay on
// filter to match this one region
MBOVERLAY._glMap.setFilter("highlightregion", ["==", 'name', name]);

// highlight overlay off
// filter to match no region ever
MBOVERLAY._glMap.setFilter("highlightregion", ["==", 'name', "Nonexistent"]);
This technique is a lot more complicated, and since you need to use filtering anyway in order to operate it, the first technique I described (a dedicated highlighting layer) gets the job done with less work. But if you are using someone else's Style and editing it is not an option, this technique would allow you to accomplish much the same effect.


Stroke vs Fill

One last note about highlighting: stroke versus fill. Mapbox layers are either polygons (a fill, with no stroke) or else lines (a boundary but no fill). If you want to highlight with both, you will need to define two layers, then set the filtering on both of them.

This goes for both doing highlights within the Mapbox Studio Style, or using the addLayer() technique.


Thursday, October 19, 2017

Leaflet-Mapbox-GL HOWTO: Filtering features on the map

My series on Mapbox GL API combined with Leaflet using leaflet-mapbox-gl.js continues.

Previously we created a function selectRegionByName() which would switch between a choropleth view and a plain-outline view, and zoom the map to a given region. Let's expand on that:

  • When we zoom in to a region, we toggle between choropleth and simple outline, and also zoom to the given area.
  • Now we also want to show the waterways and the gauges within that region, but not in other regions so as to minimize the visual noise.

Filtering Is Easy

Quite simply, this is done with setFilter() which you've already seen. In our case, the gauge points and waterway lines had already been tagged with a region attribute so filtering is quite easy. You should be able to patch these into selectRegionByName() with no difficulty.
// region selected// filter gauges and waterways layers, to match this regionMBOVERLAY._glMap.setFilter('gauges', ["==", 'region', name]);MBOVERLAY._glMap.setFilter('waterways', ["==", 'region', name]);

// null selected// filter gauges and waterways layers, to match no region at allMBOVERLAY._glMap.setFilter('gauges', ["==", 'region', 'Nonexistent']);MBOVERLAY._glMap.setFilter('waterways', ["==", 'region', 'Nonexistent']);

There's really not a lot to say about it. When an area is selected, set the filters to match only features in that region. When no area is selected, set an impossible filter.

New Filters Replace Old Filters

The real caveat here is that these filters replace your own filtering in the Style. If the gauge locations were already filtered in your Style, to show only those with "Status = Operational" then guess what? You just blew away that filter in favor of this new one: it's showing all gauges in the region regardless of their Status field.

This can mean some duplication of effort, adding the filter in your Style via Studio, then remembering to replicate that filtering here in the client side code in addition to the new region filter. An alternative, would be to use getFilter() to fetch the current set of filters, then add/remove the ones relevant to the region.

getFilter() returns the list of the filters currently applied to the layer. MBOVERLAY._glMap.getFilter("gauges") would return something like this, indicating a filter that matches ALL of the following filters, a filter clause by region and a filter clause by status.
[ "all", ['==', 'region', 'Northeastern Watershed'], ['==', 'Status', 'Operational'] ]
What we would want here, is to remove the region filter and leave all the rest, including that all at the start and any other clauses that aren't for region. And here we are:
// add a region filter// to whatever other filters were in placevar filters = MBOVERLAY._glMap.getFilter("gauges");filters.push([ '==', 'region', name ]);MBOVERLAY._glMap.setFilter('gauges', newfilters);

// clear the region filter// but re-apply any other filters previously in placevar filters = MBOVERLAY._glMap.getFilter("gauges");filters = filters.filter( (f) => { return f[1] != 'region' });MBOVERLAY._glMap.setFilter('gauges', filters);
This technique is a bit more work to set up, compared to the first example which is copy-paste in 20 seconds. But if you are already using filtering on your layers, this technique would preserve the filters already defined in the Style while also allowing you to define them client-side.

Of course, it's all dependent on your use case. If your filtering needs are fairly complex, or you're creating a whole filtering UI anyway, maybe you'd do better to define all your filters client side and keep them all in one place. 


Monday, October 16, 2017

Leaflet-Mapbox-GL HOWTO: Toggle between choropleth and boundaries

My series on Mapbox GL API combined with Leaflet using leaflet-mapbox-gl.js continues.

One of the first interesting tasks beyond just seeing the vector tiles on screen, would be to select one of those hydrology regions, then focus the map on it. When no area is selected, a statewide choropleth should indicate some statistical information about each region.
  • One of the datasets (I mean Tilesets) loaded into Mapbox is of the statewide hydrology regions. They each have a statistical field indicating their percentage completeness, and we will want a choropleth representation of it with some known breakpoints.
  • When an area is selected, we want to hide the choropleth and zoom in to that area, and switch over to a second rendition of those polygons: simple thick lines. Thus the choropleth color won't be distracting now that we're looking at a detailed view.
  • An area could be de-selected entirely, at which time we should switch back to choropleth, zoom back to statewide extent, and hide the lines.
  • The bounding box extents for each area, are present here in the client-side code: region name, west, south, north, east. So no special tricks are required there.

Adding Region Polygons to the Style


  • First step of course, was to upload the Tileset into Mapbox. Done.
  • Second, style up the two versions: a plain thick black outline when zoomed in, and a choropleth when zoomed out.
  • Solid black is pretty simple. Just click the layer name, fill in a color. Done.
  • Choropleth is more tedious but not too tough: Select the layer, and for the color hit the expander and select Enable Property Function and select a field. In my case I want to filter by value and I have category breaks already defined: I select # as the data type and Categorical as the classification. I then used "Add Stop" and entered the max values for each break, one by one.
And there we have it, a choropleth based on the completion percentage and a plain black outline. Both are visible in Mapbox Studio this whole time, but on the client side we're going to change that.


Toggling by Region Name


I wrote a function which accepts a region name, to zoom to it and highlight it and all. It also accepts null in order to zoom to the statewide view, selecting no area at all and adjusting the highlights accordingly.

We will expand on this in the coming days. Here's our starting content:
function selectRegionByName (name) {
    if (name) {
        // zoom the map to this region's already-known info
        const rawdata = REGION_INFO[name];
        MAP.fitBounds([[ rawdata.BBOX_S, rawdata.BBOX_W ], [ rawdata.BBOX_N, rawdata.BBOX_E ]]); 

        // suppress the choropleth by setting a filter that matches nothing
        // enable the black borders by not filtering
        MBOVERLAY._glMap.setFilter('waterregions_choro', ['==', 'name', '']);
        MBOVERLAY._glMap.setFilter('waterregions_black', null]);
    }
    else {
        // zoom the map to the fixed bounds of the whole state
        MAP.fitBounds(WHOLESTATE_BOUNDS);

        // allow the choropleth to show, by not filtering it
        // hide the black outlines by impossible filtering
        MBOVERLAY._glMap.setFilter('waterregions_choro', null);
        MBOVERLAY._glMap.setFilter('waterregions_black', [ '==', 'name', '']);
    }
}
The trick to toggling the layers is easy: to hide a layer, apply to it a filter which matches nothing; to show a layer, clear the filters.

It's simple now, but we will expand on this in the next few postings, so that selectRegionByName() does some more interesting behaviors.

Other Approaches to Toggling


To make the layer invisible, we could have tried a few other mechanisms. Which one works best for you, will vary by your use case. Most often, it's a case of "how would this strategy conflict with the existing map style, and cause unintended side effects?"

Filtering


For us, this layer has no filters at all. We either want to show them all or show none of them. As such, doing it by filter had few questions, and no likelihood of conflicting with our styles or layer stacking.

If you do filter your dataset to form a layer, the setFilter() route may not be for you. That use of setFilter() as shown above really does change the layer, so removes all of your filters in favor of your new filters!

addLayer() and removeLayer()


Use MAP._glMap.getLayer() to stow a reference to the choropleth layer and the black-outline layer, then call MAP._glMap.addLayer() and MAP._glMap.removeLayer() as needed. It works, though is a bit more clunky in my opinion.

Mapbox GL JS API does not support a z-index on layers, so the layer order when they are added back into the map, may not be the same as it was previously. They support a before parameter to help with the stacking order, which may work for you as long as you're not renaming layers nor changing their sequence via Mapbox Studio.

Layer Opacity


Another approach would be to alter the layer's color style via setPaintProperty() so as to give it 0 opacity.
MBOVERLAY.setPaintProperty('waterregions_choro', 'fill-opacity', 0);
MBOVERLAY.setPaintProperty('waterregions_choro', 'line-opacity', 0);
MBOVERLAY.setPaintProperty('waterregions_black', 'line-opacity', 1);
This can work well, as long as you remember to address both the stroke and the fill for all appropriate layers, and as long as you know what opacity would be "the default" when making it visible again.

Thursday, October 12, 2017

Vector Tiles with Mapbox + Leaflet

A couple of weeks back, I finally got to really dig in on Mapbox's implementation of vector tiles, and using vector tiles in Leaflet.

Myself, I almost never get to use Mapbox Studio as the cartography work usually goes to one of my coworkers who has a good eye for that stuff. We're also coming in to vector tiles a bit late, having gotten a green-light that supporting older browsers (IE 8 on XP) and operating systems (Android 4.1) was not a requirement and that a few hours of R&D would be worth the very slick interface behaviors promised by vector tiles. As such, this was a learning experience all around.

The result was a map that is really quite slick, involving behaviors which traditionally would have required a server deployment and a WMS server, and with an outcome more slick than would have been achieved with those methods anyway. Best of all, it stayed well within Mapbox's generous free tier.

The Application

  • Rivers and waterways (line), about 50,000 records spanning the entire state, about 100 MB in size. It's not the whole state, just the waterways considered interesting.
  • Several thousand stream gauge locations (point).
  • Ten defined hydrology regions (polygons) covering the state. These are to be displayed as plain black outlines as well as a choropleth based on some statistic of the waterways.
  • In the UI, a list of those regions. Picking one will zoom to the region, and will also filter the gauges and waterways to that region. The gauges and waterways are tagged with their region, so that filtering should be easy.
  • Tooltips when we mouse over waterways and gauges, and more-detailed popups when they are clicked.
  • Unspecified other Leaflet controls to be added to the map as needed: geocoders, custom legend panel, GreenInfo credits, custom scalebar, probably more.
The datasets above are fairly hefty in size, so simple GeoJSON techniques would not be appropriate here. Failing that, filtering by region would classically be a server-side phenomenon e.g. a WMS service and less-smooth interactivity.

These days, Mapbox is full bore on vector tiles. Conceptually, vector tiles brings the benefits of GeoJSON such as slick interactivity and having attribute data already in memory, with the on-demand loading of tiles, plus the server-side processing involved in generating those vector tiles efficiently by not loading every vertex of every feature.

Let's see what Mapbox can do!

Mapbox

We love Mapbox. They have a habit of changing things fairly often and sometimes breaking things, but a lot more often, they get things just right and really shine.

I rarely get to dig in to Mapbox Studio (they usually give the cartography to someone else), so I had some learning to do:
  • A dataset is called a Tileset
  • Uploading a Tileset can take a couple of hours
    In one case, the spinner never went away but I came back the next morning to find it still spinning. I reloaded the page and it had loaded just fine
  • A collection of datasets plus filtering and classifications-and-colors, organized into layers, is called a Style
    (I think of class-and-color as a style, and a collection of layers as a map, but okay...)
  • Using the Mapbox GL API, layers can be hidden and shown, can have their filtering changed at runtime, etc.

Leaflet + Mapbox GL JS API

Mapbox of course recommends their own Mapbox GL JavaScript API. While their Mapbox API really is just Leaflet with a bunch of additions and so is almost-completely compatible with third-party Leaflet extensions, Mapbox GL API is not like that.

We have all sorts of custom needs which aren't defined yet: custom map controls for legends and geocoders, maybe even Leaflet Draw at some later iteration. We're always skittish about using a semi-proprietary API that won't let us use freely define custom controls and incorporate third-party offerings, since we're all about delivering highly custom solutions.

Fortunately, the folks at Mapbox have a semi-unofficial Leaflet adapter to Mapbox GL. It works pretty well, and almost everything went perfectly as planned: the layer goes onto the map, I can toggle layer visibility and apply filters, I can publish and see the updated Style, etc.

Spoiler Alert: It's Awesome

The application came along well, giving slick interactivity, good performance, filtering capabilities, easy cartography changes as needed, and also the flexibility to incorporate arbitrary Leaflet controls and behaviors.

Along the way I learned a lot, and what I learned is the topic of the next few days' postings.

Thursday, April 13, 2017

ArcGIS tile + dynamic layer with automatic switchover

This was another interesting one to puzzle out, and turned out to be surprisingly elegant once I had wrapped my head around it.

  • The client has an ArcGIS Server with a tile service. We set up a Leaflet map for them showing these tiles, a couple of years back.
  • They now have dynamic services. They are not fast enough for production use at far-out zoom levels, but they are available at deeper scales than the tiles.
  • Can we have the map detect that they've zoomed in far enough, and silently switch between the two? Tiles when far-out and dynamic when close-in?
The answer was a comparatively simple wrapper class:
https://github.com/GreenInfo-Network/L.TileLayer.TiledAndESRIDynamicTandem

This uses the ESRI-Leaflet adapter, and creates within itself both a L.TileLayer and a L.ESRI.DynamicMapLayer. It then watches the map's zoomend event and does what it should do.

Our needs here were pretty specific, so there are a few things it does and does not support. If needs change, or someone else is interested, maybe this could be developed further.
  • It has a setOpacity() method which will apply to both sub-layers. During this I discovered and had to work around some behaviors of the dynamicMapLayer class, e.g. one cannot set its opacity if it is not in the map at that time (one can with L.TileLayer).
  • Options are passed to both layers as-given, e.g. the *attribution* is the same for both. In this case that's perfect.
Maybe this will fit a need of yours, and maybe it won't. But for me, it was a fun and interesting puzzle, and the clients couldn't be happier.


Monday, December 19, 2016

Scroll-Animated Image-Based Movies

Last week I had an interesting request that was fun to figure out. The GIS folks had put together a series of images forming an animation, as one zooms in on the California coast. Inspired by parallax image effects, they wanted to know if the image animation could be tied to scrolling the page, so the animation plays a frame at a time as you scroll.

We found a few existing toolkits that did this such as ScrollMagic, but found that the animation was not at all smooth, and that it didn't work so well for some of the cases the web designers specifically had in mind. A few of them didn't work on mobile at all.

So I ended up creating my own, and came up with two prototypes you may find interesting.

Scroll-Animated Header


This first prototype, has a top-and-center banner image on the page as with a lot of sites. But the page content locks to the height of your screen and forces scrolling, and the banner animates as you scroll.

https://github.com/GreenInfo-Network/ScrollAnimatedHeader

The effect is pretty neat, right?

This one was meant as a proof of concept and a demonstration of a technique, and not a redistributable library. Still, if you're interested you can View Source above or hit up the repo: https://greeninfo-network.github.io/ScrollAnimatedHeader/




jquery.Reanimator


Turns out that what the web folks really wanted, was for multiple, smaller image-animations to be sprinkled and embedded throughout the page content. The same way you'd normally add some float:right and float:left images throughout your text, they wanted image-animations.

So here's a look at a new jQuery plugin I created: jQuery.Reanimator.

https://greeninfo-network.github.io/jQuery.Reanimator/

 Unlike the previous one, this is specially designed to work with multiple such animations, and to not make assumptions about the page flow (e.g. no fixed header and no fixed scrolling zone). And it's implemented as a jQuery plugin, so it's almost copy-paste easy to apply to any one or any several such animations.

jQuery.Reanimator sports some neat features as well.
  • Animations can have mousemove and click effects, to play their animations. This provides alternate ways of triggering the animation should scrolling be insufficient.
  • Ability to add padding to the top and bottom of the scrollable area for an image.
  • These options can be set in the constructor, and also in data-reanimator-XXX attributes to override that global setting. Makes it easy to customize individual animations.
  • A "debug mode" to show the scrollable areas, etc. to give insight into testing and tuning the animation for your website.
For more info and to download it for your site, hit up the repo:

https://github.com/GreenInfo-Network/jQuery.Reanimator










Wednesday, November 23, 2016

Many things brewing

Happy harvest festival!

I realized the other day that it's been 5 months since my last posting. Things have been happening, but many of them are still in progress so I've kept quiet. But here's a sampling of some of what I've been working on.

AccordionLegend control for Leaflet

 

This was actually my prior blog post, back in June. It's a Leaflet control that displays a spiffy collapsing legend, with layers broken into accordion sections, with legend swatches and opacity sliders and all.

http://greeninfo-network.github.io/L.Control.AccordionLegend/

Just today, someone reported a bug with it and I fixed that bug, then went on to improve the demo, and add a few more features.

Early Warning System v2


The EWS scrapes project disclosures from several international funding banks such as the World Bank, International Funding Corporation, African Development Bank, Asian Development Bank, and others. The material is reviewed by the International Accountability Project, looking projects that could threaten human rights, e.g. involuntary relocation of a whole town, and connecting with local activists.

http://rightsindevelopment.org/?page_id=2421

I did the original EWS system back in 2011, but they want to clean things up, expand on the system, add support for other folks editing it, etc. Internal goals included some code cleanup, a nicer model structure, better error handling, a nicer search UI, and more. And, this project is in Django, which I just love, so there's a bonus.

The EWSv2 is coming along well, and preliminary feedback is quite positive. We should have the thing launched to the public in a month or three.

Tobacco retailer visualizations, next-generation system

 

A long-time client of GreenInfo Network, CounterTools has us make interactive web maps of tobacco retailers, inspections and undercover purchases of tobacco, and derivative stats such as "percentage of undercover sales which sold, by county" Our oldest maps with them go back to late 2011 or early 2012, with the latest of the current generation having been set up only a few weeks ago.

I'm working on the next generation of both the data management and mapping components. The project involves 3 agencies for 3 sections: back-end, front-end, and GIS/mapping. The mapping fits in the middle, firmly in both front-end and back-end: data models and tables, file uploads and data processing, data searching and reporting, and front-end cartography.

Unlike the current generation, this one will work with a living dataset, with new retailers and retailer inspections being added daily, so there's a whole new dimension of intelligence in the upload capabilities and error handling, in the calculations and rendering, and so on. Also unlike the current generation, the front-end is in AngularJS, and the back-end is in Django. (yay!)

I've been learning a lot from how the other teams do their job: AngularJS and Sails for the front-end, Django REST Framework for writing new APIs, their particular tactics for layout out the sections of the Django app, and so on. It's been a learning curve there, but I'm appreciating the education.

Coder Commando


I've also been handling the usual flow of miscellaneous requests that aren't large projects, but "my coder quit and I launch in two weeks!" situations. This happens a lot more often than you would imagine; four projects in the last five months, come immediately to mind.

I don't usually blog about these since they're not usually the lengthy and involved projects, but they do keep me busy. Some of my recent ones have involved some neat moving parts:
  • A tool to draw a polygon on a Google Maps map, and derive statistics from census blockgroup data, then download a PDF.
  • Learning about Expression Engine, a CMS from the folks who made CodeIgniter, and writing a bunch of fixes in various pages, some of them maps and some not.
  • A map of farms and farmers' markets statewide, with a nice CMS on the back end where one manages five pages of details about their farm. Notably, the part that lets you upload photos of your farm, has a UI for zooming and cropping the photo, so your 200x100 thumbnail looks the way you want it.

Happy Harvest

 

So yeah, I've been silent but not idle. I'm told of at least 2 new projects waiting for signatures, and some these projects in progress will likely start going live over the next few months. Once the lid is off, I can describe them in more detail.

Have a nice holiday!





Tuesday, June 14, 2016

New Leaflet control: L.Control.AccordionLegend

Some time back I came up with a custom legend control for Leaflet. Unlike the basic L.Layers control, we wanted it to be really snazzy:
  • The layer list broken into sections, not by basemap/overlay, but thematic similarity: Parks in a section, Admin Boundaries as a section, Health Statistics as a section, etc. And the sections should have accordion-style behavior: clicking a section title should expand and collapse, show only one section at a time so as not to overload the screen, and so on.
  • Each layer has an opacity slider.
  • Each layer has a legend.
So, here it is:
https://github.com/GreenInfo-Network/L.Control.AccordionLegend
http://greeninfo-network.github.io/L.Control.AccordionLegend/

Enjoy!

Friday, June 3, 2016

New Leaflet control: L.Control.CartographicScale

A request we get now and then, is to add a readout of the current map scale denominator, e.g. a readout that changes from "1:24K" to "1:12K" as you zoom in a notch. These are handy for cartographers who still think in terms of scale, instead of zoom levels.

OpenLayers had the handy-dandy OpenLayers.Control.Scale but I couldn't find a similar such control for Leaflet. So I wrote it.

http://greeninfo-network.github.io/L.Control.CartographicScale/

https://github.com/GreenInfo-Network/L.Control.CartographicScale



I should point out that the accuracy of this sort of thing, has always been dubious. Between the projection itself (a "square degree" in Lagos is not the same area as in Barrow, and Greenland is not that big in real life) and the realities of screen resolution (96dpi is for mid-90s CRTs) these scale readouts have always had very poor accuracy and always will. It's the mathematics of a world that isn't flat, you know?

Still, the control is accurate enough for cartographers to get the sense of "2K or 20K?" and that's what was really needed here.

Friday, May 20, 2016

In-Browser filtering of raster pixels in Leaflet, Part 3

In my last posting, I mentioned described the process of creating a three-band TIFF and then slicing it into three-band PNG tiles for display in Leaflet. The tiles are not visually impressive, being almost wholly black, but they have the proper R, G, and B codes corresponding to the location's PHZ, PCP, and GEZ. (if you don't know what those are, go back and read that post from a few days ago)

So now the last step: transforming these tiles based on a set of arbitrary RGB codes determined by the user. Let's go through the working source code for the L.TileLayer.PixelFilter and I'll describe how it works.

First off, we need two RGBA codes so we can color the pixels as hit or miss, and we need the list of [r,g,b] trios that would be considered a match. The initialize method accepts these as constructor params, and the various set functions allow this to be set later as well.

(The decision of what list of RGB codes should be passed into setPixelCodes() is a matter of business logic: selectors, clicks, lists... outside the scope of this discussion. See the demo code for a trivial example.)

Next, we need to intercept the map tile when it's in the browser. Thus the
tileload event handler set up in the constructor, which runs the tile through
applyFiltersToTile() to do the real work.

applyFiltersToTile() is the interesting part, which only took me a couple of hours sitting down with some HTML5 Canvas tutorials. Let's dissect it one piece at a time:
  • "copy the image data onto a canvas" The first paragraph creates a Canvas of the same width and height as the image, and copies the data into it. The IMG object itself won't let us access raw pixel data, but once it's in a Canvas we can.
  • "target imagedata" We then use createImageData() to construct a new and empty byte sequence, which can later be assigned back into a Canvas using putImageData() This is effectively a straight list of bytes, and as we write to it, we need to always write 4 bytes at a time for every pixel: R, G, B, and A.
  • "generate the list of integers" Before we start looping over pixels, a performance optimization. Arrays have the indexOf() method so we can determine whether a given value is in an array, but it only works on primitive values and not three-element arrays. The lodash library has findIndex() which would work, but it means a new dependency... and also the performance was not so great (256 x 256 = 65536 pixels per tile). So I cheat, and translate the list of desired
    pixelCodes into a simple list of integers so that indexOf() can work after all.
  • "iterate over the pixels" Now we start looping over the pixels in our Canvas and doing the actual substitution. Again, we step over the bytes in fours (R, G, B, A) and we would assign them into the output imagedata in fours as well. Each pixel is translated into an integer, and if that integer appears in the pixelcodes list of integers, it's a hit. Since indexOf() is a native function it's pretty swift, and since our pixelcodes list tends to be very short (10-50 values) the usually-avoided loop-in-loop is actually quite fast.
  • "push a R, a G, and a B" Whatever the results, we push a new R, G, B, A set of 4 bytes onto the output imagedata.
  •  "write the image back" And here we go: write the imagedata sequence back into the Canvas to replace the old data, then reassign the img.src to this Canvas's base64 representation of the newly-created imagedata. Now the visible tile isn't based on a HTTP file at all, but from a base64-encoded image in memory.
The only gotcha I found, was that upon calling setPixelCodes() the tiles would flash to their proper color and then instantly all turn into the no-match color. It worked... then would un-work itself?

The tileload event wraps the IMG element's load event. This means that when I assigned the img.src to replace the tile's visible representation... this was itself a tileload event! It would call applyFiltersToTile() again, and this time the RGB codes didn't match anything on my filters so all pixels were no-match. Worse, the assignment of img.src was again a tileload event, so it was in an infinite loop of processing the tile.

Thus the already_pixel_swapped flag. After processing the IMG element, this flag is set and
applyFiltersToTile() will skip out on subsequent runs on that IMG element. If we need to change pixel codes via setPixelCodes() that calls layer.redraw() which empties out all these old IMG elements anyway, replacing them with fresh new ones that do not have already_pixel_swapped set.

So yeah, it was an educational day. Not only did we achieve what the client asked for (the more complex version, not the simplified case I presented last week) and as a neat reusable package, but the performance is near instant.


Tuesday, May 17, 2016

In-Browser filtering of raster pixels in Leaflet, Part 2

A few days back I posted a link to L.TileLayer.PixelFilter This is a Leaflet TileLayer extension which rewrites the tiles after they have loaded, comparing each pixel against a set of pixel-codes and replacing the pixel with either a "matched" or "not matched" color. It's pretty useful for generating dynamic masks and highlights, if your back-end data is a raster and not vector data.

I had said that the client's request was to display plant hardiness zones, and that I was using the Unique Values colors as the RGB codes to match against zone codes. I lied. The reality was much more complicated than that, but would have been distracting from the end and the result. So here's the longer story.

The Rasters and the Requirement


The client has 3 rasters: Plant Hardiness Zones (PHZ), Precipitation classifications (PCP), Global Ecoregions (GEZ). Each of these is a worldwide dataset, and each has about 20 discrete integer values numbered 10 to 30ish.

The user selects multiple combination of these three factors, e.g. these two:
  • Zone 7 (PHZ=7)
  • Rainfall 20-30 inches per year (PCP=3)
  • Temperate oceanic forest (GEZ=31)

  • Zone 7 (PHZ=7)
  • Rainfall 20-30 inches per year (PCP=3)
  • Temperate continental forest (GEZ=32)
The user would then see any areas which match any of these "criteria trios" highlighted on the map. The idea is that a plant that's invasive in these areas, would also be invasive in the other areas highlighted on the map.

Fortunately, the rasters are not intended to be visible and do not need to be visually pleasing. They need to be either colored (the pixel matches any of the trios) or else transparent (not a match).

Raster To Tiles To Leaflet


Three variables and a need for one raster... sounds like we could have a three-band raster! I used ArcMap's Composite Bands tool to merge the three rasters into a three-band raster. Voila, one TIFF with three-part pixels such as (7, 3, 31) and (7, 3, 32) I just have to keep straight that R is PHZ, G is PCP, and B is GEZ.

Second, I needed to slice this up into map tiles. But it's very important that:
  • The tiles be in a format that preserves R, G, and B exactly. Something GIF or JPEG would be entirely unsuitable since GIF picks a 256-color palette, and JPEG is lossy and fudges together colors. TIFF on the other hand is not viewable in browsers as a map tile. But PNG is just perfect: RGB by default, and viewable in browsers.
  • The tile-slicing process (I picked gdal2tiles.py) must also preserve exact RGB values. The default average resampler uses interpolation, so a pixel in between a PCP=3 and PCP=2 would get PCP=2.5 and that's no good! Use the nearest neighbor resampling algorithm, which guarantees to use an existing pixel value.
Slicing up the TIFF into web-read PNGs was pretty straightforward:
gdal2tiles.py -z 0-7 -r near -t_srs epsg:3857 threeband.tif tiles

Point Leaflet at it, and I get some nearly-black tiles loading and displaying just as I expected. Well, after I remembered that gdal2tiles.py generates tiles in TMS numbering scheme, so I had to set tms:true in my L.TileLayer constructor.

I downloaded a few of the tiles and opened them up in GIMP and sure enough, that shade of black is actually (7,3,31) The tiles are not meant to be visually attractive... but those preserved RGB codes are beautiful to me.


Client-Side Pixel Detection and Swapping


That's the topic of my next posting: now that I have RGB tiles, how can I intercept them, compare them against a set of RGB codes, and appropriately color/clear pixels...? Turns out it was easier and more elegant than I had imagined.

Saturday, May 14, 2016

In-Browser filtering of raster pixels in Leaflet, Part 1

Last week I was asked to do something I haven't done before:

A client has a raster of values, this being World Plant Hardiness Zones. Each pixel is a code number, which ranges from 1 to 13. If you're into gardening, you've seen the US variation on this on the back of seed packets.

The client wants the user to select one or more hardiness zones, and have the appropriate pixels highlighted on the map. For reasons I'll cover in a later blog post, this needs to be done using the raster's RGB codes and not through some of the simpler techniques such as GeoJSON polygons with varying opacity.

I ended up writing this Leaflet TileLayer extension. It takes a list of RGB codes, and then rewrites the tile images in-canvas so as to have only two colors: those which matched and those which did not.
http://greeninfo-network.github.io/L.TileLayer.PixelFilter/
https://github.com/GreenInfo-Network/L.TileLayer.PixelFilter/

And there's our basic need filled: near-instant pixel-filtering into "selected" and "non-selected" categories, with appropriate color fill.

If you're in a hurry, there's the link to the demo and to the library. But the technical process involved, and the application of it for the client turned out to be very interesting indeed, so they will form my next few postings.

Friday, April 29, 2016

Heroku and Wordpress: Afterthoughts

The last two postings were about my successful and happy migration of my personal Wordpress site from my home PC to Heroku. It went beautifully, but a little testing and a few days revealed some improvements. One could call these Pitfalls and Gotchas about Heroku, lessons for my next app.



Database Usage / Wordpress Revisions


My MySQL dump file was 2.3 MB, fitting quite well under the 5 MB mark. Wrong. After being loaded, it bloated to about 4.1 MB and I got a warning email from Heroku that I was nearing my capacity.

First off, thank you Heroku and ClearDB. Nice job on the notification before this became a problem.

Second, what's using my disk space? I did some queries (thank you, Stackoverflow) and found that wp_posts had 450 rows... for my 35 pages. Ah yes: Page Revisions. Wordpress keeps copies of every time I've clicked Update, so there are hundreds of extra pages in there.

I trawled the net a little bit for two pieces of advice that set this right:
  • Disabling revisions (or limiting them to 1 or 2 revisions, if you prefer), with a wp-config.php modification. Easy.
  • A plugin to clean out old revisions. I then uninstalled it since disabling revisions means there won't be more to clean up.
Now my table was down to 150 posts, which is right for 30ish pages and 120ish images. My dump file was under half the previous size.

To finish the job, I had to take a dump of the table and then reload it, so as to drop and recreate the table. (databases do that, keep the space for the future; it's normally a good idea, but not here and today) And now I'm down to 1.6 MB, one third of my free tier.

Sending Email


Heroku doesn't have a sendmail setup, not even sure they have a SMTP service. So Wordpress's email capabilities were not working.

Your basic options here are:
  • Sign up for SendGrid, since Heroku has an addon for that. They have a free tier of 12,000 messages per month, which is really more than my blog could ever generate.
  • Supply your own SMTP server.

I went for the latter since I use GMail and can definitely navigate the steps of a Project, the API keys, and the GMail SMTP plugin for Wordpress. The plugin's own instructions were somewhat outdated, but that wasn't a problem. And voila, Wordpress sending email.

For your own programming, you would want to use PHPMailer or some such so you can specify your SMTP settings. A lot of things presume that there's a local sendmail or local SMTP, but not here.



So yeah, that was it. Not too awful in the "gotchas" department. Not at all! I am suitably impressed with Heroku at virtually every level: price, performance, ease of deployment once you wrap your head around it, and notifications.


Wednesday, April 27, 2016

Heroku and Wordpress: The Migration Process

My post day-before-yesterday begun the story of my migration from a home-hosted website to Heroku. Here's part two: The Migration Process

Step: Move my Media Library content into S3


First off, the uploaded photos should not be under version control; so they shouldn't be in the repository and in the ephemeral filesystem.

This was a tedious process of a few hours since I had about 130 images.
  • I set up the S3 plugin I mentioned above, made a few tests and confirmed that it's sweet.
  • I SFTP'd into my Wordpress site's wp-content/uploads folder and grabbed everything.
  • Then deleted everything from my Media Library,
  • Then uploaded it all again and watched it load into S3 and leave my uploads folder empty.
  • Then went through every posting and replaced all of the images, which of course were now broken. Annoying, but fortunately I only had 35 pages with images and did it in about 2 hours.

Step: Init repo


I'm a fan of Gitlab. They offer unlimited private repositories for free, which is really excellent. I created the repository, then followed their simple instructions to load my Wordpress files into the repo and basically turn my site into a clone.

I also created a .gitignore file with these two entries for some folders I'll be creating in a little bit. The private is where I'll do some other work I don't want in version control, e.g. working files and database dumps that I want to keep close. The vendor would be generated by composer later on, trust me.
/private/
/vendor/

Step: Add Heroku as a Secondary Master


The trick in allowing git push to push to deploy to Heroku, is that you tell your repo clone to use your Heroku as a secondary master.

heroku git:remote -a your-server-name

As of now, when pushing you will need to distinguish between git push origin master and git push heroku master. One pushes into your git repository (Gitlab, Github) and the other would redeploy to Heroku.

Step: Wordpress Updates


I then noticed that some updates were available for some plugins and for Wordpress itself. So I ran those, and after each one noted that git status reported exactly what I would expect from each upgrade. So three commits later I had Wordpress and plugins all updated, with commit notes for each update. (I could have done this before the repo init, but why not do it under version control?)

Step: Add a Procfile and composer.json file


For Heroku compatibility, it's advisable to add a Procfile and a composer.json and composer.lock file, to indicate to heroku what PHP version to prefer, that you prefer Apache over Nginx, etc. You will want these in version control.

Procfile
web: vendor/bin/heroku-php-apache2

composer.json
{
  "require" : {
    "php": "^5.6.0"
  },
  "require-dev": {
    "heroku/heroku-buildpack-php": "*"
  }
}


composer.lock is generated from the composer.json with a command:
composer update --ignore-platform-reqs

Step: Push to Heroku


All set? Then here goes:
git push heroku master
And I visit my website. And it's a Wordpress error that it can't make the database connection. That's to be expected: my wp-config.php has the old credentials and I still need to upload the database content. But that's definitely Wordpress making the error, so a fine start.

Step: Database Configuration


First step was to scrub my database credentials from the wp-config.php file. Yeah, dummy move to forget to do that, but the credentials are wrong for Heroku so are useless, and my local MySQL is going away in an hour anyway. But yes... don't do what I did. ;)

When I scrubbed the database credentials, I replaced them with $_ENV variables like this:
define('DB_NAME', $_ENV['DATABASE_BASE']);
define('DB_USER', $_ENV['DATABASE_USER']);
define('DB_PASSWORD', $_ENV['DATABASE_PASS']);
define('DB_HOST', $_ENV['DATABASE_HOST']);
Add, commit, push. Site is still dead but it's ready for this next trick.


Run heroku config and it dumps the app's configuration variables back to me. I tease apart the database URL string, into my set of 4 environment variables for the 4 $_ENV items above.
heroku config:set DATABASE_BASE='heroku_XXX' DATABASE_USER='XXX' DATABASE_PASS='XXX' DATABASE_HOST='XXX'
My app/dyno reboots and... the site's up!

Step: Database Data


A simple mysqldump was all it took to take a backup of my database, then loading it was one more command.

mysqldump -h localhost -u olduser -p olddbname > private/dbdump.sql
mysql -h herokuhost -u herokuuser -p herokudbname < private/dbdump.sql

It doesn't get as lot easier than this.

And now the site is up! My data, on a new database on a new Heroku server. Shiny.


Step: Custom Domain


My site is www.fightingfantasyfan.info and not fightingfantasyfan.herokuapp.com Heroku calls this a custom domain. There are two steps in setting up the Heroku app to work properly with a custom domain.

  • I hit up Heroku's dashboard and the Settings for my site, and added two domains for it: www.fightingfantasyfan.info and fightingfantasyfan.info This allows it to respond to these alternate hostnames, should they point to this app.
  • I went to my domain registrar's domain control panel and set up a CNAME record, so that www.fightingfantasyfan.info is equivalent to fightingfantasyfan.herokuapp.com This took a little bit to propagate, but was done about the time I finished my cup of coffee.


And that really was it. Well, almost. More on this tomorrow.


Monday, April 25, 2016

Heroku and Wordpress

This is a bit off-topic for The Map Guy since it has nothing to do with maps, directly. But it's interesting and it's about the cloud, and about software deployment. It's about... Hosting a low-volume personal Wordpress website on Heroku for free.

Introduction


I have a couple of personal websites for hobbies. I'm almost ashamed to admit that I'm using Wordpress for them, being the hardcore, bad-ass hacker that I am... but in the evenings and with nothing at stake, the convenience of Wordpress works for me.

I had been hosting my site on a Raspberry Pi at home, but the reliability just wasn't there. The Pi would crash from time to time and require rebooting. After the second time it did this while I was away on a trip, I decided it was time for a change. Even better, this is an opportunity to say Hello To The Cloud with a real-world application with no stakes involved.

Enter Heroku, my hero.

Heroku is a service that spins up virtual machines (they call them "apps"), using as their filesystem your git repository. The basic idea is this:
  • You have a git repository which contains your website: HTML, PHP, Python, Ruby, etc.
  • You create an "app" via their dashboard, also called a "dyno", and it has an URL. You then attach "Add-Ons" such as a MySQL database, a PostgreSQL database, SMTP via SendGrid, and other such services that you'll need.
  • Using Heroku's command-line "toolbelt" you add to your clone of the repository, the fact that this clone is "connected" to that app/VPS. So your clone has two masters: git push origin master for saving your code to version control as usual, and git push heroku master to deploy it to the site.
  • When you push to heroku master, Heroku resets your VPS, loading up its filesystem from your repository content. Assuming that your code works, the site works too.
  • No permanent storage ("ephemeral filesystem"). When the VPS is load-balanced to another system, or put to rest, or you push again, it's reset from your repo. This is very important if your web app will be making filesystem modifications such as accepting uploads. More on this later.
So the effect is a build-from-components server, enabling the specific services you need.

For small personal sites, free tiers for the dyno and for the add-on services may prove sufficient to host the Wordpress code and the database entirely for free. The limitations of this free tier, as relevant to my personal Wordpress site, are:
  • The dyno (the VPS itself) will go to sleep if there's no activity, and the next incoming activity to wake it up does mean some delay. The dyno must be asleep at least 6 hours per day, so using Uptime Robot to keep it awake is a no-no. The next step up to get rid of the sleeping, is only $10 per month.
  • The ClearDB MySQL database is free only to 5 MB. This may not be enough for a long-running daily blog, but for a few postings per month maybe it's just what you need. The next step up is only $10 per month for 1 GB.

Since Heroku does support PHP, and a mysqldump of my database is only 2 MB in size, this sounds right on target for a Heroku freebie.


Ephemeral Filesystem


Let me reiterate that "permanent storage" comment above. Your Heroku filesystem is a git repository. Your dyno does have the ability to write files on disk,  e.g. an uploads folder, e.g. the Media Library component of Wordpress. But you won't like it. When your dyno resets, the filesystem is reinitialized and your modifications would be lost.

By "reset" is meant a reboot, it being load-balanced onto a new server, it going to sleep and waking back up, your next git push, or using heroku config:set to change environment variables. Bye bye, uploaded files.

The up side of this is that a hack of your website, assuming it didn't damage the database, can be solved by rebooting. The down side is that you need to find someplace else for long-term storage of any web-supplied files not in your repository (or else make a practice of manually downloading the files and adding to the repo? sounds awful)

In the case of Wordpress the easiest solution I found is the WP Offload S3 Lite plugin. When you upload to the Media Library, it goes to Amazon S3 instead, and media URLs are rewritten to point to their S3 version. Between Amazon's generous 5 GB free tier for a year and the real price being a paltry 3 pence per gigabyte per month, even an image-heavy website can get by on pocket change per month.

If you are writing your own ware, you'd want to code for your cloud storage of choice such as Amazon S3, Google Drive API, Dropbox API, etc. where you supply a file and get back a URL. I imagine you'd need to generate API keys, program the OAuth-style exchange of them, handle errors etc. and that sounds awful. For my own case here, though, the folks at Delicious Brains had generously done that heavy lifting for me.


Happy Ending


Spoiler time: My applications are all running on Heroku and the performance is quite acceptable.  And I learned a lot in the process. The rest of this story is how I got to this happy place.

So, now that I've covered the basics, tomorrow's story will be about the migration process!

Monday, February 15, 2016

Some Leaflet controls for modal dialogs

A recurring need we have, is to open a dialog or a modal from within a Leaflet map. Dialogs and modals are a great way to add Feedback links, to show the legend without taking up screen space, to add a Help or About panel, etc.

A perfectly ordinary way would be a positioned DIV anchored to the edge of the screen or to the edge of the map DIV, so it looks like a "tab". You've surely seen this before for Feedback links along the edge of the screen. But this time we wanted a button in-map, something that looked like a real Leaflet button. It wasn't tough to do, cuz Leaflet rocks.

Now... having done it, why not polish it up so that next time it's copy-paste simple? Here we go:

https://github.com/gregallensworth/L.Control.BootstrapModal
https://github.com/gregallensworth/L.Control.jQueryDialog

I even took the step of making a jQuery UI version. The project last week didn't use this, but it was a small step to adapt the button code, and it will surely serve us in the future.

Enjoy!

Friday, January 8, 2016

IonicMapStarter, the Ionic successor to MobileMapStarter

At winter solstice 2012, I took a few days of vacation time and used it to create MobileMapStarter. The intent was to boil down the essential and generally-reusable bits of a mobile mapping app, strip out the application-specific stuff, and have a starting place for our future map apps. This meant:
  • A working mobile framework, with page-view management and all
  • Working around certain bugs and issues of Leaflet when used inside page-view systems
  • Working boilerplate code for geocoding, location tracking, etc.
  • The thing being designed with configuration separate from execution so it's simple to reconfigure
  • Ability to cache tiles for offline use
And it worked out famously. I presented MobileMapStarter at FOSS4G 2014 (welcome to Portland!) and was surprised at how popular it became.

But, jQuery Mobile has problems and I have been looking for a newer framework to replace it. Some weeks back I really got to like Ionic, and winter solstice 2015 has brought you...

IonicMapStarter


It's the same concept as before: a mobile app scaffold, that's easy to reconfigure and adapt to form your own mobile app. But this time it's built with Ionic. I mentioned a few weeks back some improvements which this change brought to ParkInfo Mobile:
  • Better performance all around, from the map to general page-loading and panning behavior
  • Cleaner structure from the ground up, and a reduction in code volume
  • Improved UI for the offline tile caching, as well as improved capabilities
We still aren't releasing ParkInfo Mobile until we finish some branding
 and functional tweaks, but you can start on your next-generation mobile app tonight.