Skip to content

Instantly share code, notes, and snippets.

@andygup
Last active April 17, 2017 18:19
Show Gist options
  • Select an option

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

Select an option

Save andygup/32107b63dcfce3f3c7cbbd8a8f1a77c8 to your computer and use it in GitHub Desktop.
A pubnub block for creating directions using the Esri routing service
/*
This ArcGIS-based PubNub Block shows a pattern for running the routing service to find the best way to get from one location to another or to visit several locations.
Declare the Event Handler with the export syntax. The incoming message is called request.
The request object contains a starting coordinate and an ending coordinate:
Set up the test payload
{
"start": {
"lat": 37.783,
"lon": -122.407
},
"end": {
"lat": 37.782,
"lon": -122.404
}
}
*/
export default request => {
let xhr = require('xhr');
let query = require('codec/query_string');
//Create a free developer account at developers.arcgis.com
//Setup an ArcGIS Online hosted proxy for routing. developers.arcgis.com/authentication/working-with-proxies/
//The dedicated URL should look like this http://utility.arcgis.com/usrsvcs/appservices/FXosrP0nfaTJUdDi/rest/services/World/Route/NAServer/Route_World
let apiUrl = '';
// return if the block does not have anything to analyze
let searchParam = request.message;
let lat1 = searchParam.start.lat;
let lon1 = searchParam.start.lon;
let lat2 = searchParam.end.lat;
let lon2 = searchParam.end.lon;
if (!lat1 || !lat2 || !lon1 || !lon2) {
return request.ok();
}
let queryParams = {
stops: lon1 + ',' + lat1 + ';' + lon2 + ',' + lat2,
outFields: "*",
f: 'json'
};
// To learn more about the Esri Route Service and its API visit:
// https://resources.arcgis.com/en/help/arcgis-rest-api/#/Route_service_with_synchronous_execution/02r300000036000000/
let url = apiUrl + '/solve' + '?' + query.stringify(queryParams);
return xhr.fetch(url)
.then((response) => {
return response.json()
.then((parsedResponse) => {
request.message.routes = parsedResponse;
console.log(request.message.routes);
return request;
})
.catch((err) => {
console.log('error happened on JSON parse', err);
return request;
});
})
.catch((err) => {
console.log('error happened for XHR.fetch', err);
return request;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment