Skip to content

Instantly share code, notes, and snippets.

@Plagiatus
Created March 9, 2023 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Plagiatus/54796fba7ba2e3e9859c82ef1c963491 to your computer and use it in GitHub Desktop.
Save Plagiatus/54796fba7ba2e3e9859c82ef1c963491 to your computer and use it in GitHub Desktop.
Using the Google Maps JS API in svelte
<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&region=DE"
on:load={initMap}
></script>
</svelte:head>
<div id="map" bind:this={mapElement} />
<style>
#map {
height: 500px;
margin-top: 2em;
}
</style>

Some things to note

  • 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment