Reputation: 39
I started using vue. How can I include Google API to my page? This is my code:
<template>
<div id="map"></div>
</template>
<script>
export default {
methods: {
init () {
var map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
})
}
}
}
</script>
Where can I set
<script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
Upvotes: 2
Views: 2470
Reputation: 101
I'd like to put the google map api just before </body>
. Make sure your vue element is called before google map api (i.e. within app.js). Put initMap
as the google api's callback.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="app">
<map lat="1.23456" lng="100.21345"></map>
</div>
<script src="app.js"></script><!-- your vue element should be here -->
<script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=initMap" async defer></script>
</body>
</html>
And this is my code in Map.vue
, which has a definition of window.initMap(..)
. I also have a marker (pin) inside the map.
<template>
<div>
<div ref="map" style="width: 100%; height: 200px;"></div>
</div>
</template>
export default {
props: [
'lat',
'lng'
],
mounted() {
window.initMap = () => {
this.mapElement = new google.maps.Map(this.$refs.map, {
zoom: 14,
center: {lat: this.lat, lng: this.lng}
});
this.marker = new google.maps.Marker({
position: {lat: this.lat, lng: this.lng},
map: this.mapElement
});
}
},
data() {
return {
mapElement: null,
marker: null
}
}
}
Upvotes: 0
Reputation: 3616
The script element goes in your index.html file, for example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="app"></div>
</body>
<script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
</html>
If this doesnt work for you, try removing the callback from the end of the <script>
element's src
attribute as well as the async and defer keywords, so it looks like:
<script src="https://maps.googleapis.com/maps/api/js?key=YourKey"></script>
Then in your vue instance, call your init()
function once the App component has mounted. See below:
export default {
mounted () {
this.init()
},
methods: {
init () {
var map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
})
}
}
}
Upvotes: 1