Skip to content

Instantly share code, notes, and snippets.

@yooouuri
Last active April 3, 2024 13:34
Show Gist options
  • Save yooouuri/cf3a3d5bdbce68a6281649d0c8a1dd88 to your computer and use it in GitHub Desktop.
Save yooouuri/cf3a3d5bdbce68a6281649d0c8a1dd88 to your computer and use it in GitHub Desktop.
googleMaps composable
import { Loader } from '@googlemaps/js-api-loader'
type GeocodeArgs = {
lat?: number
lng?: number
placeId?: string
}
let loader: Loader | null = null
export function useGoogleMaps() {
function initGoogleMaps() {
if (loader !== null) return
loader = new Loader({
apiKey: import.meta.env.VITE_GOOGLE_MAPS_API_KEY,
version: 'weekly',
libraries: ['places', 'geocoding', 'marker', 'maps'],
})
}
async function places(input: string, types = ['address'], language = 'nl', country = 'nl') {
const { AutocompleteSessionToken, AutocompleteService } = await loader.importLibrary('places')
const sessionToken = new AutocompleteSessionToken()
const autocompleteService = new AutocompleteService()
return await autocompleteService.getPlacePredictions({
input,
sessionToken,
componentRestrictions: {
country: [ country ],
},
language,
types,
})
}
async function geocode({ lat, lng, placeId }: GeocodeArgs): Promise<google.maps.GeocoderResult[]> {
const { Geocoder } = await loader.importLibrary('geocoding')
const geocodingService = new Geocoder()
const res = await geocodingService.geocode({
...((lat !== undefined && lng !== undefined) && { location: new google.maps.LatLng(lat, lng) }),
placeId,
})
return res.results
}
return {
places,
initGoogleMaps,
geocode,
loader,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment