After watching a few videos I’m trying to work through a problem set.
Original app took loaded stores.js (basic array of stores name and address) then it’d update a new stores array based on async calls to google api for lat long and address. The user then inputs a radius (from their geolocation) and it displays a clickable store list at the bottom of the page. Click and directions are shown.
That part works. The problem I’m having (this is homework) is i’m trying to add on the feature of localStorage; if a user input a radius prior then show those stores below when the page is refresh.
I’m still having trouble understanding async/await as I come from more of a procedural background and just can’t seem to get it to work.
Looking for feedback on the code structure, how would you do it ALL differently. I’ve been trying for about a week now and keep starting over in hopes something will click.
The below is the meat of the code, current issue is when I try to call getStoresWithinRadius() it happens before “allStoresData” is available, I believe.
// setup vars
const GOOGLEAPIKEY = "&key=xxx";
let userLocation, directionsService, directionsDisplay, distanceService, map;
const geocodeUrl =
antiCors + "https://maps.googleapis.com/maps/api/geocode/json?address=";
const distanceUrl =
antiCors +
"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=";
let allStoresData = [];
let memRadius = localStorage.getItem("radius");
// dom elements
let radius_text = document.getElementById("radius");
let locationRows = document.getElementById("locationRows");
const btnSearch = document.getElementById("btn_search");
btnSearch.addEventListener("click", function() {
getStoresWithinRadius(radius_text.value);
});
if (memRadius) {
console.log("memRadius =>", true);
radius_text.value = memRadius;
}
// show map
// get user location and sort stores by distances
// set map center to user location
function setup() {
initMap();
getPosition()
.then(position => {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
userLocation = {
lat: lat,
lng: lng
};
return userLocation;
})
.then(() => {
setupStores(userLocation);
})
.catch(err => {
console.error(err.message);
});
}
function initMap() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
distanceService = new google.maps.DistanceMatrixService();
var mapOptions = {
zoom: 3,
center: { lat: 41.8781, lng: -87.6298 }
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
}
var getPosition = function(options) {
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
};
async function setupStores(userLocation) {
stores.forEach(async function(store) {
store = await getStoreLatLong(store);
store = await getDistanceToStore(store, userLocation);
// new object array of stores with all data
allStoresData.push(store);
allStoresData.sort(sortByDistance);
});
return allStoresData;
}
async function getStoreLatLong(store) {
let geocode = geocodeUrl + store.address + GOOGLEAPIKEY;
let geoJson = await request(geocode, "json");
store.coords = geoJson.results[0].geometry.location;
return store;
}
async function getDistanceToStore(store, userCoords) {
// convert to url format
let userLoc = userCoords.lat + "," + userCoords.lng;
let distance =
distanceUrl + userLoc + "&destinations=" + store.address + GOOGLEAPIKEY;
let distJson = await request(distance, "json");
store.origin = distJson.origin_addresses[0];
store.distance = distJson.rows[0].elements[0].distance.text;
store.duration = distJson.rows[0].elements[0].duration.text;
return store;
}
async function getStoresWithinRadius(radius) {
let storesInRadius = [];
allStoresData.forEach(async function(store) {
let distance = parseFloat(store.distance.replace(/mi|,| /g, ""));
if (radius >= distance) {
storesInRadius.push(store);
} else {
}
});
console.log("Stores in rad => ", storesInRadius);
return storesInRadius;
}
// clean up distance and parse as float for comparison and reorder
function sortByDistance(a, b) {
const distA = parseFloat(a.distance.replace(/mi|,| /g, ""));
const distB = parseFloat(b.distance.replace(/mi|,| /g, ""));
let comparison = 0;
if (distA > distB) {
comparison = 1;
} else if (distA < distB) {
comparison = -1;
}
return comparison;
}