Skip to content

Commit

Permalink
feat: finished getCoordsFromAddress function
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanzitting committed Jan 17, 2022
1 parent febe6b7 commit ba50ee8
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fetch from 'cross-fetch';
import { GOOGLE_GEOCODING_SECRET_KEY } from 'config';
import { GOOGLE_GEOCODING_SECRET_KEY } from './config';

export function parseNumber(str?: string): number | undefined {
const parsed = Number(str);
Expand All @@ -11,25 +11,21 @@ export function _throw(msg: string): never {
throw msg;
}

export async function useThisFunctionWheneverYouFindYourselfInTheSituationWhereYouHaveAnAddressButYouWantCoordinates(address: string): Promise<object> {
// Prepare the address for submission to Google's API
address = address.replace(/ /g, "%20");
let requestUrl: string = `https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${GOOGLE_MAPS_API_KEY}`

// Submit it to the API
const geocodingRes = await fetch(requestUrl)
.catch(err => {
console.log(err);
});

console.log(geocodingRes);

// Process the response
const coordinates: object = {
lat: geocodingRes.geometry.location.lat,
lng: geocodingRes.geometry.location.lng
};

// Output the resulting Coordinates
return coordinates;
export async function getCoordsFromAddress(address: string): Promise<any> {
const urlAddress = address.replace(/ /g, "%20");
const requestUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${urlAddress}&key=${GOOGLE_GEOCODING_SECRET_KEY}`
const coords = {
lat: '0',
lng: '0',
}
try {
const geocodingRes = await fetch(requestUrl)
.then((res) => res.json());
const coordRes = geocodingRes.results[0].geometry.location
coords.lat = coordRes.lat;
coords.lng = coordRes.lng;
} catch (error) {
console.log(error);
}
return coords;
}

0 comments on commit ba50ee8

Please sign in to comment.