From 378955d00b44b1ed3136aa783111857fa1c08ba2 Mon Sep 17 00:00:00 2001 From: Matthew Oslan Date: Sat, 6 Jun 2020 14:26:41 -0400 Subject: [PATCH] Add Google Maps geocoder --- routes/geocoders/GoogleMaps.ts | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 routes/geocoders/GoogleMaps.ts diff --git a/routes/geocoders/GoogleMaps.ts b/routes/geocoders/GoogleMaps.ts new file mode 100644 index 0000000..237ee86 --- /dev/null +++ b/routes/geocoders/GoogleMaps.ts @@ -0,0 +1,35 @@ +import { GeoCoordinates } from "../../types"; +import { CodedError, ErrorCode } from "../../errors"; +import { httpJSONRequest } from "../weather"; +import { Geocoder } from "./Geocoder"; + +export default class GoogleMaps extends Geocoder { + private readonly API_KEY: string; + + public constructor() { + super(); + this.API_KEY = process.env.GOOGLE_MAPS_API_KEY; + if ( !this.API_KEY ) { + throw "GOOGLE_MAPS_API_KEY environment variable is not defined."; + } + } + + public async geocodeLocation( location: string ): Promise { + // Generate URL for Google Maps geocoding request + const url = `https://maps.googleapis.com/maps/api/geocode/json?key=${ this.API_KEY }&address=${ encodeURIComponent( location ) }`; + + let data; + try { + data = await httpJSONRequest( url ); + } catch ( err ) { + // If the request fails, indicate no data was found. + throw new CodedError( ErrorCode.LocationServiceApiError ); + } + + if ( !data.results.length ) { + throw new CodedError( ErrorCode.NoLocationFound ); + } + + return [ data.results[ 0 ].geometry.location.lat, data.results[ 0 ].geometry.location.lng ]; + } +}