- If you're using typescript you'll want to install
npm i -D @types/google.maps
for proper linting. - Google wants you to give the script a callback, so you know when it's loaded. For this callback to work, it needs to be defined on the global window object, and I dislike that. So I used on:load instead. This will still give you the warning in the console, but you can ignore that.
- I'm using svelte:head to load the script, because I only want it to be added if the component is added. However I haven't found a solution on how to prevent it being added multiple times if the component is used multiple times or is destroyed and re-added.
- I've also added multiple parameters like the language and region specifier, you can leave them out or adjust them to your usecase.
- This will expose your API key to the world, so make sure to limit it in the google cloud console to only work with your website.
- Talking about the API, make sure you enable Google Maps JS API for your API key for this to work. depending on what else you want to do with your map, you might need additional APIs such as Places or Geocoding.
Created
March 9, 2023 08:00
-
-
Save Plagiatus/54796fba7ba2e3e9859c82ef1c963491 to your computer and use it in GitHub Desktop.
Using the Google Maps JS API in svelte
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
let map: google.maps.Map; | |
let mapElement: HTMLDivElement; | |
const apiKey = '<your api key here>'; | |
let marker: google.maps.Marker; | |
function initMap() { | |
const start = new google.maps.LatLng(52.5069704,13.2846517); | |
map = new google.maps.Map(mapElement, { | |
// You can adjust these settings to your liking, of course | |
center: start, | |
zoom: 15, | |
streetViewControl: false, | |
clickableIcons: false, | |
mapTypeControl: false | |
}); | |
marker = new google.maps.Marker({ | |
map, | |
position: start | |
}); | |
map.addListener('click', (event: any) => { | |
//when the user clicks, set the marker at the clicked position | |
updatePosition(event.latLng); | |
}); | |
} | |
function updatePosition(latlng: google.maps.LatLng) { | |
map.setCenter(latlng); | |
marker.setPosition(latlng); | |
} | |
</script> | |
<svelte:head> | |
<script | |
src="https://maps.googleapis.com/maps/api/js?key={apiKey}&libraries=geocoding&language=de®ion=DE" | |
on:load={initMap} | |
></script> | |
</svelte:head> | |
<div id="map" bind:this={mapElement} /> | |
<style> | |
#map { | |
height: 500px; | |
margin-top: 2em; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment