我开始使用vue。如何将谷歌 API 添加到我的网页中?这是我的代码:
<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>
在哪里可以设置
<script src="https://maps.googleapis.com/maps/api/js?key=YourKey&callback=App.map" async defer></script>
脚本元素位于 index.html 文件中,例如:
<!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>
如果这对您不起作用,请尝试从<script>
元素的src
属性末尾以及 async 和 defer 关键字中删除回调,使其如下所示:
<script src="https://maps.googleapis.com/maps/api/js?key=YourKey"></script>
然后在 vue 实例中,在挂载 App 组件后调用init()
函数。见下文:
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'
})
}
}
}
我想把谷歌地图 API 放在</body>
之前。确保在谷歌地图 API 之前调用你的 vue 元素(即在 app.js 内(。initMap
作为谷歌 API 的回调。
<!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>
这是我在Map.vue
中的代码,它有window.initMap(..)
的定义。我在地图上还有一个标记(图钉(。
<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
}
}
}