【问题标题】:ERROR Error: Uncaught (in promise): ReferenceError: google is not defined错误错误:未捕获(承诺):ReferenceError:未定义谷歌
【发布时间】:2018-01-31 19:23:20
【问题描述】:

我在我的项目中使用 Angular 2 + Google Maps Places Autocomplete 它给了我这个错误:

错误错误:未捕获(承诺中):ReferenceError:未定义谷歌

这里是html:

  <agm-map  id="googleMap">

  </agm-map>

组件:

 ngOnInit() {
    var p1 = new google.maps.LatLng(45.463688, 9.18814);
    var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);

    let  directionsService = new google.maps.DirectionsService;
    let  directionsDisplay = new google.maps.DirectionsRenderer;
    let mapProp = {
        center:{lat:  30.42018, lng: -9.5981500},
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP 
    };
    let map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    directionsDisplay.setMap(map);
    this.calculateAndDisplayRoute(directionsService, directionsDisplay);
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;

//create search FormControl
this.searchControl = new FormControl();

//set current position
//this.setCurrentPosition();

  var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "ma"}
  };
  //load Places Autocomplete
  this.mapsAPILoader.load().then(() => {
  let autocomplete = new 
  google.maps.places.Autocomplete(this.searchElementRef.nativeElement, 
  options);

  });
 }

模块:

 imports: [
   AgmCoreModule.forRoot({
  apiKey: "MyOWNKEY",
  libraries: ["places"]
}),

顺便说一下,我使用的是 AGM(Angular Google Maps)

【问题讨论】:

  • 看起来像一个导入问题...
  • 我认为错误在于您的new google.maps.LatLng(45.463688, 9.18814); 行。把你的库导入,因为在这种情况下 var google 没有定义
  • 我把库导入到哪里了??
  • 我试图删除新的 google.maps.LatLng(45.463688, 9.18814);但它仍然给出同样的错误
  • 试试这个例子plnkr.co/edit/YX7W20?p=preview

标签: angular google-maps angular-google-maps


【解决方案1】:
    declare var google.

把它放在组件的顶部。

当然,还要确保您在 Angular 的 index.html 页面顶部添加了谷歌地图脚本

【讨论】:

  • 感谢您的回复,但是当我在 index .html 中声明 google 地图时,它给了我这个错误:您在此页面上多次包含 Google Maps API。这可能会导致意外错误。
  • index.html 只有 css 和 js 文件
  • 当我删除 let DirectionsService = new google.maps.DirectionsService;让方向显示 = 新的 google.maps.DirectionsRenderer;让 mapProp = { center:{lat: 30.42018, lng: -9.5981500}, zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP };让 map = new google.maps.Map(document.getElementById("googleMap"), mapProp);方向Display.setMap(地图);它有效,我不知道为什么
  • 老兄,你在页面导入谷歌地图的脚本了吗?
  • 打开你的控制台,尝试访问window.google看看它是否存在
猜你喜欢
  • 1970-01-01
  • 2014-09-02
  • 2022-06-15
  • 2014-06-05
  • 1970-01-01
  • 2020-10-30
  • 2022-12-19
  • 2020-02-29
  • 1970-01-01
相关资源
最近更新 更多