Filed under Leaflet

CodeAcross 2015: Creating an Asset Map of South Downtown Atlanta

This weekend, I attended the CodeAcross Atlanta hack weekend, run by Code for Atlanta and hosted by the Center for Civic Innovation. The topic of the hack weekend was the South Downtown neighborhood of Atlanta.

South Downtown is a neighborhood that's been long ignored and overlooked. But it's brimming with potential. The buildings are there, the density is there, and the people are arriving. South Downtown is waking up.

Our hosts at the Center for Civic Innovation are kicking off a long-term effort to shape the future of South Downtown, and Code for Atlanta is partnering with them on this goal.

We're going to get out of the building and take some walking tours of the area to get a real feel for it, then we'll hear from those who live, work, and play in South Downtown. Based on what we learn, we'll then get to business and start hacking on projects. There will be maps to make and data to open.

This is a rare opportunity to help revitalize a neighborhood at the perfect moment. South Downtown will be a great neighborhood in the near future, and you'll help shape it at CodeAcross Atlanta. —Code For Atlanta

Learning about South Downtown

To kick off our hack weekend, Luigi gave an intro to civic hacking. Then Kyle Kessler gave a presentation on the South Downtown neighborhood, past and present. He covered the formation of Atlanta as "Terminus", the Civil War and burning of Atlanta, Atlanta's reemergence, civil rights, Underground Atlanta, the Olympics, and more. This presentation provided a helpful overview to thinking about how South Downtown can be revitalized.

One nice thing about the event was that it actually occurred in South Downtown, the area of interest. CodeAcross was hosted by the Center for Civic Innovation, at the M. Rich Building. As a result, we all got to take a nice walking tour of the neighborhood, to better frame the work we would do over the weekend. Personally, I'm pretty familiar with South Downtown. I'm currently attending The Iron Yard Academy, which is located in the same building, and even before that course, I've biked through South Downtown quite a bit. That said, the walking tour was still beneficial to me. A few people in our group had detailed knowledge about the neighborhood, and it was helpful to know more details. The walking tour probably also helped make our map feel more real to the other contributors.

Three Groups

After lunch, we split up into groups. Three topic were presented, and people were allowed to choose which group they wanted to participate in.

A branding campaign and storytelling website for South Downtown that begins to change the hearts and minds of Atlantans and their impressions of the neighborhood. Yes, we need folks who can code and launch a website. But just as importantly, we need designers to think about the real-world implications of what a strong brand means for a neighborhood. And we'll need gifted storytellers to convey the gravity of the history of the neighborhood and the role it played in the civil rights movement.

An interactive asset map that comprehensively displays existing properties in the neighborhood and opportunities for economic development. We need mapping experts to write the code to build the map, but we also need people with expertise in commercial real estate and city planning to help guide the design of the map. We need volunteers to go out into the neighborhood and figure out what exactly is there, because the data about the neighborhood is in many instances incorrect or out-of-date.

A participatory tool that amplifies the voices of those who live and work in South Downtown. This tool needs to work both on-line and on-the-ground. In many instances of economic development, the powerful, monied interests coming in simply don't listen to the people already in the area. We'll build a platform that collects input from the community and actually delivers that input to key stakeholders. To design it well, it'll require the "soft skills" of listening and empathy. To make it effective, it'll need guidance from those experienced in advocacy and lobbying the powerful. —Luigi Montanez

Unsurprisingly, I chose the asset map group.

The Asset Map Group

The first step for the asset map group was to whiteboard out what layers we would like to see on the map. We also had to decide who the target audience was for the map. We came to the conclusion that it would be best to have different maps for different audiences (e.g. developers, advocates, visitors), but our focus for the weekend should be to find as many data layers as we could that would have relevance to any of the audiences. Then—after the weekend—we will split the map up into multiple maps. Here are just a few of the layers from our list of ideal data:

  • Zoning
  • Population density and demographics
  • Parking
  • Transit
  • Infrastructure
  • Organizations and social events
  • Art
  • Filming locations

Luigi was the leader of the asset map group. There were around 12 people who chose to work primarily on the asset map. We decided it would be most efficient with such a large group to split up into two sub-groups, one working on research and data, and the other sub-group working on creating the map. It was the first group's job to research each of the map layers we wanted, find if data was readily available, and if it was available, they would get it ready to send along to the map team. If it wasn't readily available, they would try to determine who might have the data and how it could be obtained.

I was the leader of the sub-group creating the map. We were tasked with making an interactive map showing all the layers of data found by the research and data cleaning team.

Making the Map

Day 1

On day one, the research and data cleaning sub-group created a google doc and drive folder and began collecting data to add to the map. Our coding sub-group got the preliminary map set up, and I threw in a couple data layers that I already had handy from previous map projects. The Leaflet newbies ran through a quick tutorial and we looked at alternative mapping platforms like Mapbox and Tilemill. Also on day 1, Bryan and Jimmy in the coding sub-group started working on a geocoder in Ruby, since we knew some of the data the researchers would provide us wouldn't have coordinates.

In our Leaflet map, we made use of a few libraries to help make our job of mapping easier and make our finished product look good quickly. Leaflet only supports GeoJSON by default, but by using leaflet-omnivore and leaflet.shapefile/shapefile-js, we are able to import CSV, GPX, shapefiles, and more. This is helpful for the fast prototyping needed to get something substantial finished over a weekend like this. We also used Font Awesome and Leaflet.awesome-markers to create impressive looking map markers rapidly.

This is what our map looked like at the end of day 1:

Day 1 Progress

Day 2

On day 2, the research and data sub-group continued finding data sources, and sent many of them along to our mapping group. They also helped us out with some GIS work by taking some of the shapefiles they had found and cropping them down to our area of interest. Additionally, they provided domain expertise, helping us interpret the data and deciding with us which data fields should be shown in map popups.

In the coding sub-group, Jimmy completed the geocoder and used it on a few of the data sources. We added those to the map, as well as adding several other point layers that already had coordinate data. During the night, I had implemented queries of the Foursquare API, so we spent some time on day 2 thinking of what kinds of venues we wanted to pull from Foursquare. We added government buildings, entertainment, residential buildings, and food from the Foursquare API. I also learned how to do image overlays, so we threw in a couple of maps the data group had gathered. Finally, we added in some shapefiles the data group had found. All-in-all, we had 14 map data layers at the end of day 2. When we presented our work, it seemed people were impressed by how much stuff is in South Downtown and at how quickly we were able to assemble and map so much of it.

Day 2

I was equally impressed with the branding/storytelling and participatory groups. The branding and storytelling group thought up neighborhood slogans and set up a preliminary website to host information about South Downtown. The participatory group came up with a basic survey that can be filled out via text or web and thought up ways to advertise the survey and engage individuals with interactive street displays. I was greatly impressed by how much we got done in a weekend project.

Even better yet, Code For Atlanta has structured a meetup so we can continue working on this project in the future. Usually when I do hackathons and other hack events, I'm disappointed by the project not continuing and often not getting to see my work get used. I'm really looking forward to meeting up once a month with the other hackers to continue our efforts.

And we certainly have plenty more to do. There's still much more data that the research team found that we haven't had a chance to implement in the map yet. There's also more data we haven't found yet, and data we haven't even begun to be sure how to measure (e.g. community). We also want to create separate maps for different audiences and integrate the map into the website.

I enjoyed helping to lead the asset mapping team, and I'm greatly looking forward to continuing to work on this project. I really care about South Downtown, and this weekend made me feel like I was helping the neighborhood, while also getting to do something I love with really great people. I highly recommend joining Code for Atlanta (or your local Code for America brigade). As I think our mapping project showed, even if you aren't a coder, there are huge ways you can contribute. Thanks to my team and to the organizers of the event for making it the best hack weekend or hackathon I've attended!

The map will eventually be available at southdowntown.org, but for now you can find the code on Github.

Tagged , ,

Book Review: Leaflet.js Essentials by Paul Crickard III

This is a review of Leaflet.js Essentials by Paul Crickard III.

Contents

  • Chapter 1 introduces creating a basic map from scratch with leaflet, how to use map tiles, how to create popups, and how to enable geolocation.
  • Chapter 2 shows how to create GeoJSON data, how to style GeoJSON layers by type (LineString, Polygon, etc.), and how to filter to display only a subset of the data.
  • Chapter 3 introduces the leaflet.heat plugin for density heat maps and the heatmap.js library for intensity heat maps. It also teaches how to style and animate heat maps, how to create choropleths, and how to use buttons outside the map to change what's shown in the map.
  • Chapter 4 introduces how to create custom markers and marker shadows as well as several markers that are available online. We also learn how to cluster markers, animate markers, and create pie or bar chart markers.
  • Chapter 5 shows how to use many ESRI resources in Leaflet, including map tiles, shapefiles, and geocoding.
  • Chapter 6 introduces using Node.JS, Python, and C# with leaflet, including getting data via AJAX calls, using MongoDB to save created map points, and creating desktop applications with C#.

Review

This is a very well laid-out, detailed guide to Leaflet. It is intended for complete newbies to Leaflet, but it provides some very advanced information as well. The book claims you should have some JavaScript knowledge before beginning, but I'm not entirely sure this is necessary, since Leaflet maps rely on only very minimal JavaScript.

I enjoyed the breadth of this book. I think the book does a great job of covering the information a beginner would need. It also provides information on a wide variety of topics like good tips for designing for mobile, a very comprehensive list of map tiles (many of these I did not know about), and information on several JavaScript libraries and Leaflet plug-ins that allow for additional functionality within the maps.

On the other hand, there is one major criticism I have with this book, especially for a beginner audience. I'm not that happy with the included code samples or how they are organized. This may just be personal preference, but I prefer books that have the "before this section" code and the "after this section" code so you can start with the before and then double-check with the after if you made an error or didn't understand something. I feel like the provided code samples made it difficult to follow along with programming while reading.

All in all, I wouldn't hesitate to recommend this book to someone beginning to learn Leaflet. For more advanced Leaflet users, there are some gems that may or may not make the book a worthwhile purchase. I will say that I use Leaflet almost every day, and I did learn several things from reading Leaflet.js Essentials.

4 out of 5 stars

Tagged ,

Add Icons to Layer Control in Leaflet

When you have multiple layers, it can help to add a legend to the map. This tutorial shows how to add icons to the layer control in Leaflet. This tutorial shows only marker layers, but you could create icons for polygon layers and use those as well.

Legend with marker icons

The following code sets up our map, layers, and the layer control. This is the standard way maps look in Leaflet, with no visual indication of which layer goes with which markers, without checking the boxes on and off.

var map = L.map('map', {
    center: [33.8, -84.4],
    zoom: 11,
        layers: [trainLayer, treeLayer]
});

var overlayMaps = {
    "Train": trainLayer,
    "Tree": treeLayer
};

L.control.layers(null, overlayMaps, {
    collapsed: false
}).addTo(map);

Default legend

In order to add a legend to the layer control, you can simply change the overlayMaps code to add any HTML you'd like. In this case, we'll add the map icon pngs with a small height so they will look okay in the layer control:

var overlayMaps = {
    "<img src='http://mollietaylor.com/skills/js/leaflet/train.png' height=24>Train": trainLayer,
    "<img src='http://mollietaylor.com/skills/js/leaflet/arbol.png' height=24>Tree": treeLayer
};

It's really that simple! I searched the documentation and the web, and I couldn't figure out how to do this, so I figured I'd just try adding the HTML. Turns out it looks great!

Full code available on CodePen. Map icons by Nicolas Mollet and Axel Rodriguez.

Tagged , , ,

Changing Leaflet Slidemapper to a Side-by-Side View

The default setup in slidemapper is to have the slides either above or below the map. However, it is also possible to place the slides to one side of the map.

Slides beside map

CSS changes

We need to make a couple of changes to how the smapp-show and smapp-map classes are displayed. You'll want to play around with these some, but this is what worked well for me:

.smapp-show { 
    width:50%; 
}
.smapp-show .slide { 
    overflow-y:visible; 
}
.smapp-map { 
    margin:10px; 
    width:48%; 
    height:95%; 
    position:absolute; 
    top:0; 
    right:0; 
}

Slidemapper changes

On the slidemapper side of things, the only edit we need to make is changing the options of our slideshow. Specifically, we need to edit the slideHeight and mapHeight to something appropriate for having the slides beside the map. For example, I chose:

$mySlideMap = $('#slideshow-container').slideMapper({
    slideHeight: 540,
    mapHeight: '98%'
});

And that's all the changes you need to make to have a side-by-side slideshow in slidemapper! The full code is available as a gist.

References

Tagged , , , ,

Link to Another Slide in Leaflet Slidemapper

The slidemapper plugin for Leaflet is very useful, but when building large slideshows, it can be annoying that there is no easy way to link to specific slides. For example, you might want to create a table of contents or link from the last slide back to the first. Fortunately, there's a way to move to specific slides, instead of just advancing or moving back by 1. We'll use jQuery to do this. We already have jQuery loaded for slidemapper.

Specify Where Links Will Go

After the $mySlideMap code in your html file, you can create a list of links that you will later add to the slides. Generally, this will be the last thing in the <script> tag at the end of the body.

For example, in the sample code from the slidemapper example, the <script> initially contains:

$mySlideMap = $('#slideshow-container')
.slideMapper();

$mySlideMap.slideMapper('add', EXAMPLEDATA);

At the end of the script, let's add a link to the first slide and a link to the last slide. The jQuery we use allows any code with a specific class to be transformed into a link. We can combine that with the slidemapper move method to create links to specific slides.

$('.toc').click(function() {
    $mySlideMap.slideMapper('move', 0, true);
});

$('.end').click(function() {
    $mySlideMap.slideMapper('move', EXAMPLEDATA.length - 1, true);
});

Add the Links

Next, we need to actually include the links in the slides. The links references will go in the data file. In the example, the file is named data.js.

Here's a link to the last slide from the first slide:

// intro marker
{
    icon: 'other.png',
    marker: [42.516846, -70.898499],
    center: [40.423, -98.7372],
    html: '<table style="margin:0 40px; padding:10px"><tr>' +
            '<td><img src="http://placehold.it/300x180&text=Map+Stuff"/></td>' +
            '<td style="padding-left:10px">' +
                '<h1>SlideMapper FTW!</h1>' +
                '<p>This is a demo of the different sorts of slides you can setup using slidemapper.</p>' +
                '<p><a class="end">Skip to the end.</a></p>' +
            '</td>' +
        '</tr></table>',
    popup: 'So it begins!'
},

And here's a link from the last slide to the first slide:

// empty slide
{
    html: '<div style="margin:0 40px; padding:20px 10px">' +
            '<div>' +
                '<h2>The End</h2>' +
                '<p>Goodbye.</p>' +
                '<p><a class="toc">Return to Table of Contents.</a></p>' +
            '</div>' +
        '</div>'
}

Prettifying

Because of the unusual way these links are made using jQuery, we should probably add some css to make them look like links. I added the following css to the <head>, but you can add any css to the head or as a separate stylesheet.

<style type="text/css">
    a {
        color: orange;
        cursor: pointer;
        text-decoration: underline;
    }
</style>

Here's an example of a link from one slide to another

And now you have an easy way to navigate through a long slidemapper deck. You could even create a table of contents at the beginning and then link back to that from each slide.

The full code is available in a gist.

References

Tagged , , , , , , ,

Center Map on Layer Change in Leaflet

In Leaflet, it can be helpful to change the bounds of the map when the user adds or changes the visible map layers.

The Basics

First, we'll start with the initial code including our map and polygon layers:

var circle = L.circle([51.508, -0.11], 500, {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
});

var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]);

var map = L.map('map', {
    center: [51.505, -0.09],
    zoom: 13
});

var overlayMaps = {
    "Circle": circle,
    "Polygon": polygon
};

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
}).addTo(map);

L.control.layers(overlayMaps, null, {
    collapsed: false
}).addTo(map);

So far, most of this should be familiar from the Leaflet Quick Start Guide.

Next, we want to add a listener function that will zoom and re-center upon a change in the circle or polygon layer.

The .on method of map allows you to watch for an event to occur and then execute a function when it does. In this case, we want to wait for the event 'baselayerchange'. This way the map will automatically zoom and recenter when the user changes layers.

map.on('baselayerchange', function(e) {
    console.log(e);
    map.fitBounds(e.layer);
});

The map automatically zooms to the bounds of the shape when the layer is activated.

Options

There are a few options for exactly how the map is zoomed and/or re-centered and for what type of layers are affected.

If you want to do this with overlay layers instead of base layers, you can substitute 'overlayadd' for 'baselayerchange'. Using overlay layers is more common for drawing shapes, but treating your layers as base layers makes it easy to display only one at a time.

map.on('overlayadd', function(e) {
    console.log(e);
    map.fitBounds(e.layer);
});

fitBounds automatically zooms to the tightest zoom level where the whole shape is visible. If you don't want to use fitBounds (say you're centering on a new overlay layer and don't want to zoom all the way in), you can use setView or panTo instead. panTo animates as the view changes.

map.on('overlayadd', function(e) {
    console.log(e);
    map.panTo(e.layer);
});

And there you have a few different ways to center and/or zoom in when an overlay layer is added or when the baselayer is changed. I'd recommend you check out the documentation for fitBounds, setView, and panTo and play around with the options. The options for L.control.layers are also helpful. For example, you can set collapsed to false to encourage users to change the layers.

The full code is available in a gist.

References

Tagged , , , , , , ,

LWIMW3: Trail Magic

I just finished my submission for Look What I Made Weekend 3. Look What I Made Weekend (LWIMW) is a chance for people to create something over the course of 48 hours. The concept is based on Ludum Dare and other game jams, but for LWIMW you don't have to make a game. Instead, you are free to pursue any creative endeavor and show off your results at the end.

NB: The content below is mostly a reprint of my submission at LWIMW.

My project is an interactive website that will be part of the companion site to a book my friend Scott Thigpen is writing. I didn't quite start from scratch on this project. This image shows the progress I had made before the weekend. You can also view it on the web.

pre-LWIMW

The other images show the current status after the weekend.

I made a lot of progress this weekend. I added GPS routes to the map, added a table of contents, added marker clustering, improved the graphic design (CSS and basemap), and added about 25% of the final content.

post-LWIMW

post-LWIMW

The only essential things I have left to do are adding the rest of the content, working with my friend on palette and graphics, and tweaking some small things.

You can view the current state of the Trail Magic site here.

Tagged , , , , ,

Append Layer to overlayMaps in Leaflet

What if we want to create a layer based on geolocation, but have the layer only be added to the map once geolocation occurs? I didn't find this example in any Leaflet tutorials, but it's pretty simple with some basic JavaScript

I'll start with some code that should look familiar from the Leaflet Quick Start Guide, but with each item as its own layer.

var marker = L.marker([51.5, -0.09]);

var circle = L.circle([51.508, -0.11], 500, {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
});

var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]);

var map = L.map('map', {
    center: [51.505, -0.09],
    zoom: 13,
    layers: [marker, circle, polygon]
});

var overlayMaps = {
    "Marker": marker,
    "Circle": circle,
    "Polygon": polygon
};
L.tileLayer('http://tile.cloudmade.com/[API-KEY]/29889/256/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
  maxZoom: 18
}).addTo(map);

Next let's add the code that will display the three original layers if geolocation does not occur. In this case, we do not want the geolocated layer to show.

function onLocationError(e) {
    alert(e.message);

    L.control.layers(null, overlayMaps).addTo(map);
}

map.on('locationerror', onLocationError);

You can see in the below screenshot that only the three layers are displayed.

With geolocation off

Finally, we need to add code that will display all the layers (including the geolocation layer) if geolocation does occur. We simply need to add the "yourLocation" layer to overlayMaps and then display the layers as normal.

function onLocationFound(e) {
    yourLocation = L.marker(e.latlng);

    overlayMaps["You"] = yourLocation;

    L.control.layers(null, overlayMaps).addTo(map);
}

map.on('locationfound', onLocationFound);

The screenshots below show what happens once geolocation has occurred.

With geolocation on

Showing geolocation layer

The full code is available in a gist.

References

Tagged , , , ,

Add and Remove Leaflet Circle on Click

Similar to the popup example in the Leaflet tutorial, you might want to allow a user to add a circle centered on the point they click.

After defining your map, you first need to declare the variable you'll be using:

var clickCircle;

While popups automatically disappear on the next click, circles do not. The following code removes the former circle from the leaflet map before drawing the new circle:

function onMapClick(e) {
    if (clickCircle != undefined) {
        map.removeLayer(clickCircle);
    };

Next, we want our function to draw the new circle (NB: "1609 * 3" is the radius of the circle. This makes the radius equal 3 miles):

    clickCircle = L.circle(e.latlng, 1609 * 3, {
        color: '#f07300',
        fillOpacity: 0,
        opacity: 0.5
  }).addTo(map);
}

And finally, we need to add an event listener so that the function will be run when a user clicks on the map:

map.on('click', onMapClick);

The full code is available in a gist.

References

Tagged , , , , ,

Embed Audio in Leaflet Pop-up

Here's how to embed audio in a leaflet map. This example will also show you how to embed most other HTML in a leaflet map, or how to embed audio in an HTML file.

In your map code:

function onEachAudio(feature, layer) {
    layer.bindPopup(feature.properties.name + "<br>" + feature.properties.html);
};

new L.GeoJSON.AJAX("audio.geojson", {
    onEachFeature: onEachAudio,
    pointToLayer: function(feature, latlng) {
      return L.marker(latlng, {icon: audioIcon});
    }
}).addTo(map);

And here's the geojson format where you'll include your audio HTML and the coordinates where you want to view each file:

{
    "type": "FeatureCollection",
    "features": [
    {
        "type": "Feature",
        "properties": {
            "name": "<a href='http://www.freesound.org/people/genghis%20attenborough/sounds/212798/'>Deep basement</a>",
            "html": "<p><audio width='300' height='32' src='http://www.freesound.org/data/previews/212/212798_205108-lq.mp3' controls='controls'><br />Your browser does not support the audio element.<br /></audio></p>"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-100,34]
        }
    },{
        "type": "Feature",
        "properties": {
            "name": "<a href='http://www.freesound.org/people/John%20Sipos/sounds/125696/'>Atlantis docks then lands.</a>",
            "html": "<p><audio width='300' height='32' src='http://www.freesound.org/data/previews/125/125696_593024-lq.mp3' controls='controls'><br />Your browser does not support the audio element.<br /></audio></p>"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-84,40]
        }
    }
    ]
}

Just substitute in the address of your audio files for the sample files above in the "html" property of the geojson features.

Example Leaflet map with audio

The full code is available in a gist.

Tagged , , , , ,