【发布时间】:2019-10-26 04:52:00
【问题描述】:
我正在尝试按照本教程将谷歌地图添加到我的 vuejs 应用程序:https://markus.oberlehner.net/blog/using-the-google-maps-api-with-vue/
我有一个 id="maps" 和 ref="mapsection" 的 div。我尝试使用 document.getElementById 和 this.ref 将映射实例与 div 绑定,但我得到了 null/undefined 错误。有人可以告诉我我做错了什么吗?当我进入检查模式时,我看到了创建的 div。
我已经尝试了以下两种方法,其中“mapsection”是 ref,“map”是 div 的 id。
const map = new google.maps.Map(this.refs.mapsection);
const map = new google.maps.Map(document.getElementById('map'));
查看代码:
<el-row>
<div ref="mapsection" id="map" style="width:100%;height:400px">
</div>
</el-row>
脚本代码:
async mounted() {
try {
console.log(document.getElementById('map')); //returns null
const google = await gmapsInit();
const geocoder = new google.maps.Geocoder();
const map = new google.maps.Map(document.getElementById('map')); //tried this.refs.mapsection as well.
const locations = [{
position: {
lat: 48.160910,
lng: 16.383330
}
}]
geocoder.geocode({ address: 'Austria' }, (results, status) => {
if (status !== 'OK' || !results[0]) {
throw new Error(status);
}
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
const markers = locations.map(x => new google.maps.Marker({ ...x, map }));
});
} catch (error) {
console.error(error);
}
}
我遇到的错误:
与
this.refs.mapsection>TypeError: Cannot read property 'mapsection' of undefined与
document.getElementById('maps')>TypeError: Cannot read property 'firstChild' of null
【问题讨论】:
标签: google-maps vue.js vuejs2