Skip to content

Commit

Permalink
Refactor google maps singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
bpetermann committed Aug 20, 2023
1 parent 2401118 commit 4ffb91a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
22 changes: 19 additions & 3 deletions src/helpers/googleMaps.ts
Original file line number Diff line number Diff line change
@@ -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<string, { lat: number; lng: number } | undefined> = 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
Expand All @@ -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
Expand All @@ -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)
})
})
}
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useSortCitiesByDistance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4ffb91a

Please sign in to comment.