Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | 1x 110x 25x 1x 1x 3x 3x 13x 3x 3x 1x 3x 11x 56x 56x 56x 11x 11x 11x 11x 11x 5x 5x 3x 1x 4x 4x 4x 4x 3x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x | import * as R from 'ramda';
// helper functions
const findValueBy = R.curry((src, filterKey, searchStr, key) => {
const found = (obj) => R.includes(searchStr, obj[filterKey]);
return R.compose(R.prop(key), R.find(found))(src);
});
const addressLens = R.lensPath([ 'results', '0', 'address_components' ]);
export const transformPredictionResponse = (predictions, options = {}) => {
const { requestCity, requestState, requestZipcode } = options;
const extractPrediction = (prediction) => {
return { description: prediction.description, placeId: prediction.place_id };
};
let scoredPredictions = null;
if (!(requestCity || requestState || requestZipcode)) {
scoredPredictions = predictions.map(extractPrediction);
}
scoredPredictions = predictions.map((row) => {
const result = {
description: row.description,
place_id: row.place_id
};
const cityMatch = row.terms.filter((term) => requestCity && term.value === requestCity).length > 0 ? 1 : 0;
const stateMatch = row.terms.filter((term) => requestState && term.value === requestState).length > 0 ? 1 : 0;
const zipMatch = row.terms.filter((term) => requestZipcode && term.value === requestZipcode).length > 0 ? 1 : 0;
result.score = cityMatch + stateMatch + zipMatch;
result.stateMatch = !requestState || (requestState && stateMatch);
result.zipCodeMatch = !requestZipcode || (requestZipcode && zipMatch);
return result;
}).filter(
rec => !!rec.stateMatch && !!rec.zipCodeMatch
).sort((a, b) => {
Eif (a.score === b.score) {
return 0;
}
return a.score < b.score ? 1 : -1;
}).map(extractPrediction);
return scoredPredictions;
};
export const parsePlacesAddress = (res) => {
const placeResult = res.results ? res.results[0] : res.result;
Iif (!placeResult || R.isEmpty(placeResult)) {
return {};
}
let addressComponents = null;
if (res.results) {
addressComponents = R.view(addressLens)(res);
} else {
addressComponents = placeResult.address_components;
}
const findAddressComponentByType = findValueBy(addressComponents, 'types');
const formattedAddress = placeResult.formatted_address;
const latitude =
placeResult.geometry &&
placeResult.geometry.location &&
placeResult.geometry.location.lat
? placeResult.geometry.location.lat
: null;
const longitude =
placeResult.geometry &&
placeResult.geometry.location &&
placeResult.geometry.location.lng
? placeResult.geometry.location.lng
: null;
const streetNumber = findAddressComponentByType('street_number', 'short_name') || '';
const streetRoute = findAddressComponentByType('route', 'long_name') || '';
const street1 =
(streetNumber || streetRoute) && `${streetNumber} ${streetRoute}`;
const address = {
state: findAddressComponentByType('administrative_area_level_1', 'short_name'),
city:
findAddressComponentByType('locality', 'short_name') ||
findAddressComponentByType('sublocality', 'short_name') ||
findAddressComponentByType('neighborhood', 'long_name') ||
findAddressComponentByType('administrative_area_level_3', 'long_name') ||
findAddressComponentByType('administrative_area_level_2', 'short_name'),
street_1: street1.trim(),
country: findAddressComponentByType('country', 'short_name'),
zipcode: findAddressComponentByType('postal_code', 'long_name'),
latitude: latitude && Number(latitude),
longitude: longitude && Number(longitude),
formattedAddress
};
return R.filter(Boolean)(address);
};
class GeoService {
constructor (mapsKey) {
this.mapsKey = mapsKey;
}
async geocode (address) {
const res = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${this.mapsKey}`
);
const response = await res.json();
return parsePlacesAddress(response);
}
async geocodeZip (zipCode) {
const res = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?components=country:US|postal_code:${zipCode}&key=${this.mapsKey}`
);
const response = await res.json();
return parsePlacesAddress(response);
}
async reverseGeocode (lat, lng) {
const res = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${this.mapsKey}`
);
const response = await res.json();
return parsePlacesAddress(response);
}
async geoLocate () {
// https://developers.google.com/maps/documentation/geolocation/overview
// NOTE: also returns accuracy (95% confidence of lat, lng in meters)
const url = `https://www.googleapis.com/geolocation/v1/geolocate?key=${this.mapsKey}`;
const requestConfig = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
};
const request = await fetch(url, requestConfig);
const response = await request.json();
const { lat, lng } = response.location;
return this.reverseGeocode(lat, lng);
}
async getLocationSuggestions (payload) {
/*
https://developers.google.com/maps/documentation/places/web-service/autocomplete
Component should use session token: https://developers.google.com/maps/documentation/places/web-service/autocomplete#sessiontoken
**/
const { input, latitude, longitude, radius } = payload;
const { requestCity, requestState, requestZipcode } = payload;
const location = R.join(',', R.filter(Boolean, [ latitude, longitude ]));
let { sessiontoken } = payload;
if (!sessiontoken) {
sessiontoken = crypto.randomUUID().replaceAll('-', '');
}
const params = R.filter(Boolean, {
input,
sessiontoken,
location, // The point around which to retrieve place information.
radius, // The radius parameter must also be provided when specifying a location
components: 'country:US',
types: 'address',
key: this.mapsKey
});
let queryString = '';
if (params) {
const searchParams = new URLSearchParams(params);
queryString = searchParams.toString();
}
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?${queryString}`;
const requestConfig = {
method: 'GET',
headers: {
Accept: 'application/json'
}
};
const request = await fetch(url, requestConfig);
const response = await request.json();
let autocompletePredictions = [];
if (response.predictions && response.status === 'OK') {
const options = { requestCity, requestState, requestZipcode };
autocompletePredictions = transformPredictionResponse(response.predictions, options);
}
return { autocompletePredictions, sessiontoken };
}
async getPlaceId (payload) {
const { placeId, sessiontoken } = payload;
const params = R.filter(Boolean, {
place_id: placeId,
sessiontoken,
key: this.mapsKey
});
let queryString = '';
if (params) {
const searchParams = new URLSearchParams(params);
queryString = searchParams.toString();
}
const url = `https://maps.googleapis.com/maps/api/place/details/json?${queryString}`;
const res = await fetch(url);
const response = await res.json();
return parsePlacesAddress(response);
}
async getNavigatorPosition () {
// check if navigator is available
// NOTE: also returns accuracy (95% confidence of lat, lng in meters)
// TODO: check accuracy and only return if within acceptable limit, provided in payload
const handleError = (error) => {
console.error(error);
};
(navigator.geolocation && navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
return this.reverseGeocode(lat, lng);
},
handleError
)) || handleError({ message: 'geolocation is not enabled.' });
}
}
export default GeoService;
|