Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release v2.1 - Reduce Mapbox API Consumption #8

Merged
merged 3 commits into from
Jan 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"no-alert": 0,
"no-debugger": 2,
"no-return-assign": [1, "always"],
"no-plusplus": 0,
"max-len": [1, {
"code": 150,
"tabWidth": 2
Expand Down
4 changes: 2 additions & 2 deletions ios/lightrail/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>2.0</string>
<string>2.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>3</string>
<string>6</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>comgooglemaps</string>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"node": "^6.9.2"
},
"dependencies": {
"geolib": "^2.0.24",
"moment": "2.15.2",
"prop-types": "15.5.10",
"react": "15.3.2",
Expand Down
2 changes: 1 addition & 1 deletion src/components/StationCard/StationCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default class StationCard extends React.Component {

renderDistanceText = () => {
const { stationIndex, stationDistances, mode } = this.props;
if (stationDistances) {
if (stationDistances && stationDistances[stationIndex].duration) {
return `${stationDistances[stationIndex].durationText} ${mode === 'driving' ? 'drive' : 'walk'}`;
}
return null;
Expand Down
40 changes: 37 additions & 3 deletions src/helpers/mapboxDistanceAPI.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,48 @@
import geolib from 'geolib';
import { mapboxApiKey } from './config';


const orderByDistance = (origin, destinations) => {
const currentLocation = { latitude: origin[1], longitude: origin[0] };
const stations = destinations.map(latlng => ({ latitude: latlng[1], longitude: latlng[0] }));

const nearestStationDistances = geolib
.orderByDistance(currentLocation, stations)
.slice(0, 3)
.sort((a, b) => a.key - b.key);

const nearestStationCoordinates = nearestStationDistances.map(item => destinations[item.key]);
const nearestStationIndices = nearestStationDistances.map(item => item.key);

return { coordinates: nearestStationCoordinates, indices: nearestStationIndices };
};

export const mapboxDistanceAPI = {
getDistance(origin, destinations, mode) {
const coordinates = destinations;
coordinates.unshift(origin);
// First, get the nearest three stations as-the-crow-flies, to save on API calls.
const { coordinates, indices } = orderByDistance(origin, destinations);

// Prepare the URL for the GET request.
coordinates.unshift(origin);
const endpoint = `directions-matrix/v1/mapbox/${mode}`;
const coordinatesString = coordinates.map(coordinate => coordinate.toString());
const coordinatesQuery = coordinatesString.join(';');
const url = `https://api.mapbox.com/${endpoint}/${coordinatesQuery}?sources=0&access_token=${mapboxApiKey}`;
return fetch(url).then(res => res.json());

// Fetch the datat from the Mapbox API.
return fetch(url)
.then(res => res.json())
.then(res => res.durations[0].slice(1)) // remove our current location from the results
.then((res) => { // build out an array representing the station distances, with null values for stations that were not queried
const distances = [];
for (let i = 0; i < destinations.length; i++) {
if (indices.includes(i.toString())) {
distances.push(res.shift());
} else {
distances.push(null);
}
}
return distances;
});
}
};
34 changes: 18 additions & 16 deletions src/scenes/RailMap/RailMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,27 +223,29 @@ export default class RailMap extends React.Component {
.map(stop => [stop.latlng.longitude, stop.latlng.latitude]);

mapboxDistanceAPI.getDistance(origin, destinations, mode)
.then((res) => {
const stationDistances = res.durations[0]
.slice(1) // get rid of first item, which is the distance of current location to itself (0)
.map((duration, index) => ({ index, duration, durationText: distanceTimeConverter(duration) })); // this index is used to map to blueStops index

const nearestStation = stationDistances.reduce((prev, curr) => {
if (prev.duration < curr.duration) {
return prev;
}
return curr;
});
const nearestIndex = nearestStation.index;
.then((durations) => {
console.log(durations);
const stationDistances = durations
.map((duration, index) => ({
index, // this index is used to map to blueStops index
duration,
durationText: duration ? distanceTimeConverter(duration) : ''
}));

const nearestStationIndex = stationDistances
.filter(item => item.duration)
.sort((a, b) => a.duration > b.duration)[0]
.index;

// set station marker colors
this.setNearestMarkerColor(nearestIndex);
this.setNearestMarkerColor(nearestStationIndex);

// REVIEW: Parts of updatedStationDistances might be superfluous. Refactor as necessary.
const updatedStationDistances = {};
stationDistances.forEach((stop, index) => {
updatedStationDistances[`stopCallout${index}`] = {
...this.state[`stopCallout${index}`],
durationText: distanceTimeConverter(stationDistances[index].duration),
durationText: stationDistances[index].duration ? distanceTimeConverter(stationDistances[index].duration) : '',
inbound: getNextTrainTime('inbound', index),
outbound: getNextTrainTime('outbound', index)
};
Expand All @@ -253,13 +255,13 @@ export default class RailMap extends React.Component {
...updatedStationDistances,
connected: true,
loading: false,
nearestStationIndex: nearestIndex,
nearestStationIndex,
stationDistances
});

// Show nearest station callout. We pass stationDistances because sometimes showCallout() gets
// called before the setState above happens, and showCallout depends on stationDistances.
this.showCallout(nearestIndex, stationDistances);
this.showCallout(nearestStationIndex, stationDistances);
})
.catch((err) => {
this.setState({ error: 'mapboxDistanceAPI' });
Expand Down
4 changes: 4 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2334,6 +2334,10 @@ generate-object-property@^1.1.0:
dependencies:
is-property "^1.0.0"

geolib@^2.0.24:
version "2.0.24"
resolved "https://registry.yarnpkg.com/geolib/-/geolib-2.0.24.tgz#eb3d7fbc65f5ea3354a5af6054563ebe9f33e5f4"

get-caller-file@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5"
Expand Down