Skip to content

Instantly share code, notes, and snippets.

@andygup
Created March 22, 2017 23:25
Show Gist options
  • Select an option

  • Save andygup/a135b75496088c6c2bbe6d4d6d8328a3 to your computer and use it in GitHub Desktop.

Select an option

Save andygup/a135b75496088c6c2bbe6d4d6d8328a3 to your computer and use it in GitHub Desktop.
Pubnub block for running an ArcGIS demographic analysis request via an ArcGIS Online hosted geoenrichment service.
/*
This ArcGIS-based pubnub block shows a pattern for running powerful demographic data searches.
Declare the Event Handler with the export syntax. The incoming message is called request.
The request object can either be a single point or a polygon. Here is an example, 'y' is Latitude
and 'x' is Longitude:
{
"x": -122.435,
"y": 37.785
}
*/
export default (request) => {
// Require XHR to make external calls
const xhr = require("xhr");
// Require console to print debug information
const console = require('console');
// Need a token? Create a free developer account at developers.arcgis.com
// Information on auto-majically generating a token: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000m5000000
const url = "PROXY_SERVICE_URL";
try {
// NOTE: The manually created developer access token expires in 24 hours ;-)
const http_options = {
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
// For more info on variable names: http://doc.arcgis.com/en/esri-demographics/
"body":"f=json" +
"&studyAreas=[{'geometry':{'x':" + request.message.lon + ",'y':" + request.message.lat + "}}]" +
"&analysisvariables=['populationtotals.TOTPOP_CY','Wealth.MEDHINC_CY','5yearincrements.MEDAGE_CY']"
};
return xhr.fetch(url, http_options).then((x) => {
const body = JSON.parse(x.body);
//console.log("Response payload: " + x.body);
// Remove everything but attributes information to cleanup the console output
// You can get a description of the attributes here: https://developers.arcgis.com/rest/geoenrichment/api-reference/get-variables.htm
const totalPopulation = body.results[0].value.FeatureSet[0].features[0].attributes.TOTPOP_CY;
const medianHouseholdIncome = body.results[0].value.FeatureSet[0].features[0].attributes.MEDHINC_CY;
const medianAge = body.results[0].value.FeatureSet[0].features[0].attributes.MEDAGE_CY;
console.log(
"Total Population: " + totalPopulation +
", Median Household Income: " + medianHouseholdIncome +
", Median Age: " + medianAge
);
request.message.data = {
"totalPopulation":totalPopulation,
"medianHouseholdIncome": medianHouseholdIncome,
"medianAge": medianAge
};
return request.ok();
}).catch((x) => {
console.log("Exception in xhr request: " + x);
});
} catch (e) {
console.error('Uncaught exception:', e);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment