Skip to content

Instantly share code, notes, and snippets.

@jcarbaugh
Created February 19, 2015 19:11
Show Gist options
  • Save jcarbaugh/096db3b233da2529a5d6 to your computer and use it in GitHub Desktop.
Save jcarbaugh/096db3b233da2529a5d6 to your computer and use it in GitHub Desktop.
Tweet at the legislators that represent your ZIP code
<!doctype html>
<!--
Replace YOUR-API-KEY-HERE with your API key.
Register for a key at http://sunlightfoundation.com/api/
-->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tweet at Congress</title>
</head>
<body>
<form id="tweet-form">
<label for="zipcode-input">ZIP code</label>
<input type="text" name="zipcode" id="zipcode-input" value="20877">
<button>Tweet your Legislators</button>
</form>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$("#tweet-form").submit(function(ev) {
ev.preventDefault();
var params = {
zip: $("input[name=zipcode]").val(),
apikey: "YOUR-API-KEY-HERE"
};
var apiUrl = "https://congress.api.sunlightfoundation.com/legislators/locate";
$.getJSON(apiUrl, params, function(data) {
var text = data.results.reduce(function(prev, item) {
return item.twitter_id ? prev + "@" + item.twitter_id + " " : prev;
}, ".");
var url = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(text);
window.location = url;
});
});
</script>
</body>
</html>
@kathrynmcg
Copy link

Thank you! This is great! How do I add a filter to return just house members?

@jcarbaugh
Copy link
Author

@kathrynmcg the legislators/locate endpoint on our Congress API doesn't support additional filtering, so we'd have to do it in code. Line 28 is a bit dense so I'd expand it and add the chamber check there. Replace

return item.twitter_id ? prev + "@" + item.twitter_id + " " : prev;

with

if (item.chamber === 'house' && item.twitter_id) {
    return prev + "@" + item.twitter_id + " ";
}
return prev;

One thing to note about ZIP codes, they don't map cleanly to Congressional districts. My ZIP code, 20877, overlaps MD-6 and MD-8 so our API will return both John Delaney and Chris Van Hollen since it doesn't have enough information to determine the exact district. If you can get the user's latitude and longitude, we can do an exact district lookup. The var params definition on line 21 would change to:

var params = {
    latitude: $("input[name=lat]").val(),
    longitude: $("input[name=lon]").val(),
    apikey: "YOUR-API-KEY-HERE"
}

Hope that helps!

@kathrynmcg
Copy link

That is perfect, thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment