From 4ffb91ac6f48d8f274a92c48bee8b467edbb98f6 Mon Sep 17 00:00:00 2001 From: Benjamin Petermann Date: Sun, 20 Aug 2023 10:05:20 +0200 Subject: [PATCH] Refactor google maps singleton --- package.json | 2 +- src/helpers/googleMaps.ts | 22 +++++++++++++++++++--- src/hooks/useSortCitiesByDistance.tsx | 2 +- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 4121dbb..eee7e91 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "use-sort-cities-by-distance", - "version": "1.0.6", + "version": "1.0.7", "description": "Sorts an array of cities by proximity to a point", "main": "./dist/cjs/index.js", "module": "./dist/esm/index.js", diff --git a/src/helpers/googleMaps.ts b/src/helpers/googleMaps.ts index f3280c4..0534b12 100644 --- a/src/helpers/googleMaps.ts +++ b/src/helpers/googleMaps.ts @@ -1,14 +1,24 @@ import { Loader } from '@googlemaps/js-api-loader' class GoogleMaps { - key: string + key!: string globalMaps: typeof google.maps | undefined + private static instance: GoogleMaps + coordinatesCache: Map = new Map() - constructor(key: string) { + private constructor(key: string) { this.key = key this.globalMaps = undefined } + public static getInstance(key: string): GoogleMaps { + if (!GoogleMaps.instance) { + GoogleMaps.instance = new GoogleMaps(key) + } + + return GoogleMaps.instance + } + async getMaps() { if (this.globalMaps) { return this.globalMaps @@ -24,6 +34,10 @@ class GoogleMaps { } async getCoordinates(address: string) { + if (this.coordinatesCache.has(address)) { + return this.coordinatesCache.get(address) + } + const maps = await this.getMaps() if (!maps) return undefined @@ -37,7 +51,9 @@ class GoogleMaps { return } const { lat, lng } = results[0].geometry.location - resolve({ lat: lat(), lng: lng() }) + const coordinates = { lat: lat(), lng: lng() } + this.coordinatesCache.set(address, coordinates) + resolve(coordinates) }) }) } diff --git a/src/hooks/useSortCitiesByDistance.tsx b/src/hooks/useSortCitiesByDistance.tsx index 407fb22..9a39b71 100644 --- a/src/hooks/useSortCitiesByDistance.tsx +++ b/src/hooks/useSortCitiesByDistance.tsx @@ -29,7 +29,7 @@ const useNearestLocation = ({ list, key, start = '', targets = [], unit = 'mile' useEffect(() => { const sortByDistance = async () => { const cities = list ? list : undefined - const googleMaps = key ? new GoogleMaps(key) : undefined + const googleMaps = key ? GoogleMaps.getInstance(key) : undefined if (!start || !targets.length || (!list && !key)) { return