TypeError:使用vue js显示街景全景时,无法读取null的属性'firstChild'

时间:2018-04-15 20:35:03

标签: javascript google-maps vue.js vuejs2 google-street-view

我正在尝试使用VueJS中的Google Maps API显示街景全景图 我关注了Google地图文档https://developers.google.com/maps/documentation/javascript/examples/streetview-simple?hl=fr,这是模板部分:

 <div id="map"></div>
 <div id="pano"></div>

这是脚本部分:

mounted() {
var fenway = { lat: 42.345573, lng: -71.098326 };
var latlng = new google.maps.LatLng(42.345573, -71.098326);
map = new google.maps.Map(document.getElementById('map'), {
  center: latlng,
  zoom: 14
});


var panorama = new google.maps.StreetViewPanorama(
  document.getElementById("pano"),
  {
    position: fenway,
    pov: {
      heading: 34,
      pitch: 10
    }
  }
);
map.setStreetView(panorama);
}

我在index.html中提到了这个

  <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"> 
   </script>

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,所以我在main.js中加载了脚本

export const loadedGoogleMapsAPI = new Promise( (resolve,reject) => {

window['initialize'] = resolve;

let GMap = document.createElement('script');

GMap.setAttribute('src',
'https://maps.googleapis.com/maps/api/jskey=API_KEY&callback=initialize');
document.body.appendChild(GMap); 
 });

然后我将其导入我的组件中:

import { loadedGoogleMapsAPI } from "@/main";

然后我在mounted()中调用了initialize函数:

  mounted() {
loadedGoogleMapsAPI.then(() => {
  console.log("loaded");
  this.initMap();
});
},
methods: {
initMap() {
  const element = document.getElementById(this.mapName);
  console.log(this.mapName);
  const options = {
    zoom: 14,
    center: new google.maps.LatLng(this.station.lat, this.station.lng)
  };
  const map = new google.maps.Map(element, options);
  var panorama = new google.maps.StreetViewPanorama(
        document.getElementById(this.panoName), {
          position: new google.maps.LatLng(this.station.lat, 
          this.station.lng),
          pov: {
            heading: 34,
            pitch: 10
          }
        });
    map.setStreetView(panorama);
  }
  }

我希望这对你有用