Google maps Vuejs+;谷歌地图>;document.getElementById和this.refs为div返回null
我正在尝试按照以下教程将google地图添加到我的vuejs应用程序: 我有一个id=“maps”和ref=“mapsection”的div。我尝试使用document.getElementById和this.ref将maps实例与div绑定,但出现null/undefined错误。有人能告诉我我做错了什么吗?我在进入检查模式时看到创建的div 我尝试了以下两种方法,其中“mapsection”是ref,“map”是div的idGoogle maps Vuejs+;谷歌地图>;document.getElementById和this.refs为div返回null,google-maps,vue.js,vuejs2,Google Maps,Vue.js,Vuejs2,我正在尝试按照以下教程将google地图添加到我的vuejs应用程序: 我有一个id=“maps”和ref=“mapsection”的div。我尝试使用document.getElementById和this.ref将maps实例与div绑定,但出现null/undefined错误。有人能告诉我我做错了什么吗?我在进入检查模式时看到创建的div 我尝试了以下两种方法,其中“mapsection”是ref,“map”是div的id const map=new google.maps.map(thi
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>
我收到的错误:
使用this.refs.mapsection
类型错误:无法读取未定义的属性“mapsection”
使用document.getElementById('maps')
TypeError:无法读取null的属性“firstChild”
引用的教程不使用el行
。你的问题与谷歌地图无关
要调试,请尝试这些方法中的一种
将所有装入的放在异步$nextTick
中以确保渲染
将您的代码移出el行、el表等,并移入div以隔离问题
< L> >代码> REFS/COD>在循环中通常是<代码>数组< /代码>,所以当你最终得到这个工作时,这是要考虑的事情。
我将地图分离成一个单独的组件,并将其导入视图中,它成功了。
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);
}
}