Building CampaignHawk: Styling the Precinct Data Layer (Part 20)

Sam Corcos
3 min readSep 14, 2015

--

So now we have two arrays: one that has the scaled political affiliation of each precinct and one that has the colors that are associated with those precincts. Now we need to use that information to apply styles to each precinct so they appear on our map with the appropriate color (red for Republican, blue for Democrat). When it’s finished, it should look like the image below.

You might be surprised at how easy this is. We can simply apply the styling within the properties of our polygon by using simplestyle syntax.

You may recall that we also have an array called precinctConcaveHulls, which contains an array of polygons that make up the FeatureCollection that displays on our map. The format looks like the image below.

Thanks to simplestyle, all we need to do to apply styles to each of these polygons is map over each polygon and add the following properties with the corresponding color in the scaledColorArray:

title
stroke
stroke-opacity
stroke-width
fill
fill-opacity

Within a map function, we’re going to add each of those properties. Remember that an array is an ordered list, so we can just use the index of the array to find the proper color.

let scaledPrecinctConcaveHulls = _.map(precinctConcaveHulls, function(polygonFeatureGroup, i) {
...
}

And within that map function, we’re going to create an empty object that we’ll populate with each of those properties:

let propertiesObject = {
title: precinctKeys[i],
stroke: scaledColorArray[i],
"stroke-opacity": 0.7,
"stroke-width": 2,
fill: scaledColorArray[i],
"fill-opacity": 0.3
};

Then we set the value properties to the propertiesObject and return the polygonFeatureGroup, which gives us the same polygon, but with colors associated with it.

polygonFeatureGroup.properties = propertiesObject
return polygonFeatureGroup

Then the last thing we need to do is change our feature layer to take in scaledPrecinctConcaveHulls:

let precinctFeatureLayer = 
L.mapbox.featureLayer(scaledPrecinctConcaveHulls);
map.addLayer(precinctFeatureLayer);

Then when you run the function by changing toggling the radio buttons, you’ll get something that is much more useful.

Next Steps

The next thing we should do is make a more complex and interactive data layer. I think including a slider that allows you to filter out voters who are not likely to participate in the next election would be helpful.

--

--

Sam Corcos

Software developer, founder, author - CarDash - Learn Phoenix - SightlineMaps.com