I'm really new with Svelte and I'm trying to make a web component that calls the places autocomplete library of Google. I made it to load the library on my Svelte component, but when I want to pass the autocomplete function to my input it show me the error: InvalidValueError: not an instance of HTMLInputElement.
This is what I tried so far:
<svelte:head>
<script
defer
async
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDaZc7Jr7pDoK3TWcDiv-SjqiJ0iKz15Go&libraries=places&callback=initMap">
</script>
<script>
function initMap() {
const input = document.getElementById("autocomplete");
const options = {
componentRestrictions: { country: "us" },
fields: ["address_components", "geometry", "icon", "name"],
strictBounds: false,
types: ["establishment"],
};
const autocomplete = new google.maps.places.Autocomplete(input, options);
}
</script>
</svelte:head>
This is how my input looks like:
<input
type="text"
id="autocomplete"
name="store"
class="pac-target-input"
value=""
/>
It seems like your input hasn't been rendered to the DOM when you call the initMap() method, therefore your input variable is null. Svelte offers a onMount handler which runs after the component is first rendered to the DOM.
Inside this handler, you can call your initMap() function:
import { onMount } from 'svelte';
onMount(() => {
initMap();
});
More details: Svelte Docs