Skip to content

Commit

Permalink
Replace PlaceIDs with addresses and coordinates (#108)
Browse files Browse the repository at this point in the history
* Replace PlaceIDs with addresses and coordinates

* Remove test timeout

* Increase timeout limit

* Readd done

* Increase test timout to 60 s

* Add descriptions

Co-authored-by: Malcolm Jones <[email protected]>
  • Loading branch information
danabreo and Malcolm Jones authored Jul 29, 2020
1 parent 2a0aade commit 059b773
Show file tree
Hide file tree
Showing 10 changed files with 18 additions and 122 deletions.
1 change: 0 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ app.post('/data/organizations/:id', data.organizationsPost);
app.get('/data/categories', (req, res) => {
data.getCategories().then((categories) => res.send(categories));
});
app.get('/data/update/placids', data.updatePlaceIDs);

http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"name": "step-node-starter",
"version": "1.0.0",
"description": "Skeleton app for Node.js based STEP capstone project. ",
"description": "Donatia app",
"main": "index.js",
"scripts": {
"create-env-dev": "printenv > .env.dev",
"create-env-prod": "printenv > .env.prod",
"test": "NODE_ENV=development ./node_modules/.bin/mocha --exit",
"test": "NODE_ENV=development ./node_modules/.bin/mocha --timeout 60000 --exit",
"start": "NODE_ENV=production node app.js",
"dev": "NODE_ENV=development node app.js",
"lint": "eslint --fix .",
Expand Down
7 changes: 2 additions & 5 deletions public/js/dashboardInfoForm.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* global google Handlebars */
import {getAddressFromPlaceID} from '/static/js/global.js';

/**
* Gets the information of the organization assigned to the current user.
Expand All @@ -26,9 +25,7 @@ function initAutocomplete() {
const autocomplete = new google.maps.places.Autocomplete(addressInput);
autocomplete.setFields(['place_id', 'geometry', 'name']);
autocomplete.addListener('place_changed', function () {
const place = autocomplete.getPlace();
if (!place.place_id) return;
document.getElementById('placeID').value = place.place_id;
autocomplete.getPlace();
});
}

Expand Down Expand Up @@ -57,7 +54,7 @@ window.onload = async function populateForm() {
return;
}

document.getElementById('address').value = await getAddressFromPlaceID(formJSON.placeID);
document.getElementById('address').value = formJSON.address;
document.getElementById('name').value = formJSON.name;
document.getElementById('description').value = formJSON.description;
document.getElementById('phone').value = formJSON.phone;
Expand Down
3 changes: 1 addition & 2 deletions public/js/discover/discover.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {createOrganizationCards, selectCard} from './searchList.js';
import {initMap, setLocationInfo, createMarkers, selectMarker, removeAllMarkers} from './maps.js';
import {initMap, createMarkers, selectMarker, removeAllMarkers} from './maps.js';

/* global categories */

Expand Down Expand Up @@ -58,7 +58,6 @@ async function updateSearchResults() {
data = await (await fetch('/discover/' + unparsedFilter)).json();
}

await Promise.all(data.organizations.map(setLocationInfo));
document.getElementById('loading-container').style.display = 'none';
createOrganizationCards(data.organizations, data.isLoggedIn);
createMarkers(data.organizations);
Expand Down
11 changes: 0 additions & 11 deletions public/js/discover/maps.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import {getAddressFromPlaceID, getCoordinatesFromPlaceID} from '/static/js/global.js';

const HOUSTON_COORDS = {lat: 29.7604, lng: -95.3698};

let map;
Expand Down Expand Up @@ -95,12 +93,3 @@ export function removeAllMarkers() {
for (const marker of markers) marker.marker.setMap(null);
markers = [];
}

/**
* Sets the address and coordinates of an organization using PlaceId.
* @param {JSON} organization The organization to set location info for.
*/
export async function setLocationInfo(organization) {
organization.address = await getAddressFromPlaceID(organization.placeID);
organization.coordinates = await getCoordinatesFromPlaceID(organization.placeID);
}
51 changes: 0 additions & 51 deletions public/js/global.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* global google*/

/**
* Formats a raw phone number into a +# (###) ### - #### format.
* @param {number} number The phone number unformatted.
Expand All @@ -12,52 +10,3 @@ export function formatPhoneNumber(number) {
}
return number;
}

/**
* Geocodes the placeID into an address
* @param {number} placeID Google Places ID
* @return {string} the formatted address
*/
export function getAddressFromPlaceID(placeID) {
const geocoder = new google.maps.Geocoder();
return new Promise(function (resolve, reject) {
geocoder.geocode({placeId: placeID}, function (results, status) {
if (status === 'OK') {
if (results[0]) {
resolve(results[0].formatted_address);
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
resolve();
});
});
}

/**
* Gets the latitude and longitude given a placeID
* @param {number} placeID Google Places ID
* @return {*} Object with latitude and longitude
*/
export function getCoordinatesFromPlaceID(placeID) {
const coordinates = {};
const geocoder = new google.maps.Geocoder();
return new Promise(function (resolve, reject) {
geocoder.geocode({placeId: placeID}, function (results, status) {
if (status === 'OK') {
if (results[0]) {
coordinates.lat = results[0].geometry.location.lat();
coordinates.lng = results[0].geometry.location.lng();
resolve(coordinates);
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
resolve();
});
});
}
5 changes: 2 additions & 3 deletions public/js/moreInfo.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* global Handlebars */

import {getAddressFromPlaceID, formatPhoneNumber} from '/static/js/global.js';
import {formatPhoneNumber} from '/static/js/global.js';

const organizationInfoTemplate = `
<h1>{{organization.name}}</h1>
<div id="contact-section">
<a href="https://www.google.com/maps/dir/?api=1&destination={{organization.lat}},{{organization.lng}}&destination_place_id={{organization.placeID}}"><ion-icon name="map-outline"></ion-icon>{{organization.address}}</a>
<a href="https://www.google.com/maps/dir/?api=1&destination={{organization.coordinates.lat}},{{organization.coordinates.lng}}"><ion-icon name="map-outline"></ion-icon>{{organization.address}}</a>
<a href="tel:{{organization.phone}}"><ion-icon name="call-outline"></ion-icon>{{organization.phone}}</a>
<a target="_blank" href="{{organization.website}}"><ion-icon name="globe-outline"></ion-icon>{{organization.website}}</a>
<a href="mailto:{{organization.email}}"><ion-icon name="mail-outline"></ion-icon>{{organization.email}}</a>
Expand Down Expand Up @@ -57,7 +57,6 @@ export function loadOrganizationInfo() {
fetch(`/data/organizations/${organizationID}`)
.then((response) => response.json())
.then(async (data) => {
data.address = await getAddressFromPlaceID(data.placeID);
data.phone = formatPhoneNumber(data.phone);
document.getElementById('info-section').innerHTML = renderOrgInfo({organization: data});
});
Expand Down
51 changes: 6 additions & 45 deletions routes/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,16 +336,12 @@ exports.organizationsGet = async function (req, res) {
exports.organizationsPost = async function (req, res) {
const newOrgData = req.body;

// If placeID was not populated, retrieve it.
if (newOrgData.placeID == '') {
const placeJSON = await (
await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${newOrgData.address}&key=${process.env.MAPS_KEY}`
)
).json();
newOrgData.placeID = placeJSON.results[0].place_id;
}
delete newOrgData.address;
const placeJSON = await (
await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${newOrgData.address}&key=${process.env.MAPS_KEY}`
)
).json();
newOrgData.coordinates = placeJSON.results[0].geometry.location;

newOrgData.acceptsDropOff = !!newOrgData.acceptsDropOff;
newOrgData.acceptsPickUp = !!newOrgData.acceptsPickUp;
Expand All @@ -357,41 +353,6 @@ exports.organizationsPost = async function (req, res) {
res.redirect('/dashboard');
};

exports.updatePlaceIDs = async function (req, res) {
// Get all entries from the Organizations table.
const organizations = await firestore.collection(resolveCollectionName('Organizations')).get();

let tasksCompleted = '';

await Promise.all(
organizations.docs.map(async (doc) => {
const oldPlaceID = doc.data().placeID;
const placeName = doc.data().name;

if (oldPlaceID) {
// If the current entry has a placeID, check if it is the latest one.
const placeJSON = await (
await fetch(
`https://maps.googleapis.com/maps/api/place/details/json?place_id=${oldPlaceID}&fields=place_id&key=${process.env.MAPS_KEY}`
)
).json();
const newPlaceID = placeJSON.result.place_id;

// Update the current doc's placeID if a newer placeID has been retrieved.
if (!!newPlaceID && newPlaceID != oldPlaceID) {
doc._ref.update({
placeID: newPlaceID,
});
tasksCompleted += `Updated ${placeName}. `;
}
} else {
tasksCompleted += `Missing placeID: ${placeName}. `;
}
})
);
res.json(tasksCompleted);
};

exports.getFavorites = async function (req, res) {
// If user is not authenticated then return no authorized
if (!req.user) {
Expand Down
6 changes: 5 additions & 1 deletion test/test-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,14 @@ it('GET Request /data/organizations/:id : Get an Organization', function (done)

it('POST Request /data/organizations/:id : Update an Organization', function (done) {
const newName = 'test name';
const oldAddress = '535 Portwall St, Houston, TX 77029';
const requestOptions = {
headers: {'content-type': 'application/json'},
url: process.env.BASE_URL + `data/organizations/${mockData.ORG_ID_FOOD_BANK}`,
body: JSON.stringify({name: newName}),
body: JSON.stringify({
name: newName,
address: oldAddress,
}),
};
request.post(requestOptions, function (error, response, body) {
expect(response.statusCode).to.equal(302);
Expand Down
1 change: 0 additions & 1 deletion views/dashboardProfile.handlebars
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@

<label for="address">Address</label><br />
<input disabled required type="text" id="address" name="address" /><br />
<input type="hidden" id="placeID" name="placeID" />

<label for="phone">Phone</label><br />
<input disabled type="number" id="phone" name="phone" /><br />
Expand Down

0 comments on commit 059b773

Please sign in to comment.