Reputation: 952
I'm attempting to pull in a Google Map from the Google Maps API into my Vue.js application. I have retrieved my generated API key and I am trying to display the map. When I run the app, Atom throws a Module not found error message and the browser displays: Can't resolve 'https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap' in 'C:\Atom Projects\Project\client\src\components'
Any idea what I'm doing wrong?
MyComponent.vue
<template>
<div>
<div id="map">
</div>
</div>
</template>
<script>
function initMap () {
var options = {
zoom: 8,
center:{lat:39.9612,lng:-82.9988}
}
var map = new google.maps.Map(document.getElementById('map'), options);
}
</script>
<script async defer type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap">
</script>
<style>
#map{
height: 400px;
width: 100%;
}
</style>
Full Error from Browser
./src/components/MyComponent.vue
Module not found: Error: Can't resolve 'https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap' in 'C:\Atom Projects\MyProject\client\src\components'
@ ./src/components/MyComponent.vue 8:0-131 9:0-144
@ ./src/router/index.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js
Upvotes: 1
Views: 2168
Reputation: 135752
You can't add external <script>
s to single file components like that.
The usual approach to cases like yours is to use one of the many libs that integrate vue and google maps.
Some of these libs make available new custom elements for you to use:
<gmap-map>
;<googlemaps-map>
;<map>
.All of them have simple details to setting the key and instantiating maps. Refer to their page for examples and usage.
Another one that takes a more low-level approach is Js-GoogleMapsLoader. I'm not saying this one is better than the others -- overall those that are specifics to vue probably will give you an easier integration in the long run --, but since it does not have an example with Vue, here's how you could use it:
npm install --save google-maps
change MyComponent.vue to:
<template>
<div>
<div id="map">
</div>
</div>
</template>
<script>
import GoogleMapsLoader from 'google-maps'
export default {
mounted: function () {
GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
GoogleMapsLoader.load(function(google) {
var options = {
zoom: 8,
center:{ lat: 39.9612, lng: -82.9988 }
}
var map = new google.maps.Map(document.getElementById('map'), options);
});
}
}
</script>
<style>
#map{
height: 400px;
width: 100%;
}
</style>
And none of the options above need the additional <script>
tag.
Upvotes: 1