【问题标题】:Vuejs + Google Maps > document.getElementById and this.refs returning null for a divVuejs + Google Maps > document.getElementById 和 this.refs 为 div 返回 null
【发布时间】: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);
      }
    }

我遇到的错误:

  1. this.refs.mapsection > TypeError: Cannot read property 'mapsection' of undefined

  2. document.getElementById('maps') > TypeError: Cannot read property 'firstChild' of null

【问题讨论】:

    标签: google-maps vue.js vuejs2


    【解决方案1】:

    引用的教程不使用el-row。您的问题与谷歌地图无关。

    要调试,请尝试其中的一种

    1. 将所有mounted 放入异步$nextTick 以确保渲染。

    2. 将您的代码从 el-row、el-table 等中移出并放入 div 以隔离问题。

    3. refs in loops 通常是 array,所以当你最终让它工作时,这是需要考虑的事情。

    【讨论】:

    • 我将地图分离成单独的组件并导入到视图中,它起作用了。
    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2015-02-02
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多