Reputation: 171
I am attempting to present the user with a map when they type an address into a text field. I have been able present a map at run time but am struggling to add the map on click as the error
"initMap is not a function"
How can I add the map after runtime in a js file?
Upvotes: 0
Views: 64
Reputation: 46
I suspect you’ve included a callback
query parameter when including the Google Maps API, e.g., <script src="https://maps.googleapis.com/...?key=yourkey&callback=initMap></script>
.
When you use that parameter, you are essentially telling Google Maps to automatically execute the function you specify (in this case, initMap
) as soon as the API is finished loading. So, firstly, you’ll want to omit that query param if it isn’t relevant to your use case. That should clear up your JavaScript error, and then you can use something like this to spawn maps on the page:
function handleClick() {
const mapEl = document.querySelector("#map")
new google.maps.Map(mapEl, {
center: { lat: -25.363, lng: 131.044 },
zoom: 8
});
}
someButton.addEventListener("click", handleClick);
Upvotes: 2
Reputation: 375
I am not sure what you are trying to do since there is no code but might
document.onload = function () {}
Be the thing you are looking for
(Have you searched around yet there are plenty of guides/docs with the google maps api)
Upvotes: 0