Skip to content

Instantly share code, notes, and snippets.

@heaversm
Created October 25, 2022 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heaversm/bd7dc5d144cc2c946bb0f42c405cab24 to your computer and use it in GitHub Desktop.
Save heaversm/bd7dc5d144cc2c946bb0f42c405cab24 to your computer and use it in GitHub Desktop.
all-company-trip co2 estimator
let totalPeopleInDirectory = 0;
let peopleWithUnknownLocation = 0;
let numLocations;
const locations = [];
const addPersonToTotal = function () {
totalPeopleInDirectory += 1;
};
const addToPeopleWithUnknownLocation = function () {
peopleWithUnknownLocation += 1;
};
function* traverse(o, path = []) {
for (var i in o) {
const itemPath = path.concat(i);
yield [i, o[i], itemPath, o];
if (o[i] !== null && typeof o[i] == "object") {
yield* traverse(o[i], itemPath);
}
}
}
const checkForLocation = function (personData) {
const { location, officeLocation } = personData;
if (location !== "" || location !== null) {
return location;
} else if (officeLocation !== "" || officeLocation !== null) {
return officeLocation;
} else {
return null;
}
};
async function getOrgChart() {
fetch("./orgchart.json")
.then((response) => {
return response.json();
})
.then((data) => {
const orgChart = data.forrest;
for (var [key, value, path, parent] of traverse(orgChart)) {
if (key === "data") {
addPersonToTotal();
const personLocation = checkForLocation(value);
if (personLocation) {
locations.push(personLocation);
} else {
addToPeopleWithUnknownLocation();
}
}
}
//with locations from org chart, get the geocoded lat lng of their city
let curLocation = 0;
const locationLatLng = [];
const GEOAPIFY_KEY = "[MY_GEOAPIFY_KEY]";
locations.forEach((address, index) => {
const geocodingUrl = `https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent(
address
)}&apiKey=${GEOAPIFY_KEY}`;
fetch(geocodingUrl)
.then((result) => result.json())
.then((featureCollection) => {
curLocation += 1;
if (featureCollection.features.length === 0) {
console.error("address not found");
} else {
const foundAddress = featureCollection.features[0];
const latlng = [
foundAddress.properties.lat,
foundAddress.properties.lon,
];
locationLatLng.push(latlng);
}
if (curLocation === numLocations) {
//with all locations assigned a lat and lng, get nearest airport to that coordinate
const AVIATION_EDGE_KEY = "[MY_AVIATION_EDGE_KEY]";
const numLocs = locLatLng.length;
const ALLOWED_DISTANCE = 200; //how far from coords to search for an airport
const nearestAirport = [];
let curLoc = 0;
const fetchNearestAirport = async function (location, index) {
const response = await fetch(
`https://aviation-edge.com/v2/public/nearby?key=${AVIATION_EDGE_KEY}&lat=${location[0]}&lng=${location[1]}&distance=${ALLOWED_DISTANCE}`
);
const data = await response.json();
curLoc += 1;
if (data.length) {
const airport = data[0].codeIataAirport;
nearestAirport.push(airport);
console.log(nearestAirport);
} else {
console.log("No airport found");
}
if (curLoc === numLocs) {
console.log("All airports found");
//with all locations assigned a nearest airport, get co2 emissions from airport to event
const numLocs = nearestAirports.length;
let curLoc = 0;
const co2e = [];
let totalCO2e = 0;
const CLIMATIQ_KEY = "[MY_CLIMATIQ_KEY]";
const getCO2FromAirport = async function (location, index) {
const response = await fetch(
`https://beta3.api.climatiq.io/travel/flights`,
{
method: "POST",
headers: {
Authorization: `Bearer ${CLIMATIQ_KEY}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: `{"legs":[{"from": "${location}","to": "HNL","passengers": 1,"class": "economy"}]}`,
}
);
const data = await response.json();
curLoc += 1;
console.log(data);
if (data?.co2e) {
const co2 = data.co2e;
co2e.push(co2);
totalCO2e += co2;
} else {
console.log("No co2e found for", index, location);
}
if (curLoc === numLocs) {
//DONE!
console.log("All co2e found");
console.log(co2e);
console.log(totalCO2e);
//this will be the one-way emissions of all flights from nearest airports
//for found locations to HNL from the company directory
//assuming direct 1 passenger economy flights for now
//we will use this to calculate round trip emissions for the estimated number of people who attended the event
}
};
nearestAirports.forEach((airport, index) => {
getCO2FromAirport(airport, index);
});
}
};
locLatLng.forEach((loc, index) => {
fetchNearestAirport(loc, index);
});
}
});
});
});
}
const init = async function () {
getOrgChart();
};
//on document ready
doc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment