【问题标题】:Google Maps API loads from html file, but not on local hostGoogle Maps API 从 html 文件加载,但不在本地主机上
【发布时间】:2017-07-26 00:21:36
【问题描述】:

我正在尝试通过 AngularJS 应用程序从本地主机连接到 Google Maps API,但地图没有出现,地图请求也没有到达谷歌。 html正在找到javascript文件,并且正在控制台中输出test1,但没有调用initMap并且没有输出test2。我预计它会失败,因为没有与 Google 建立 https 连接。

当我在浏览器中打开 html 文件时,地图加载正常,但是当我在本地主机上运行它时,什么也没有出现。

这是我的html代码:

<script src="client/services/maps.client.services.map.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{API_KEY}}&callback=initMap"></script>

和javascript(map.js):

console.log('test1');
function initMap() {
  console.log('test2');

  //Markers
  var markers = [
      ['Cardiff', 51.4539, -3.1694, 'city/cardiff'],
      ['Swansea', 51.6148, -3.92927895, 'city/swansea']
  ];

  // Initialise map
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: 51.4539, lng: -3.1694}
  });

  var bounds = new google.maps.LatLngBounds();
  for( i = 0; i < markers.length; i++ ) {
    // Plot pin for each place
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
      position: position,
      map: map,
      title: markers[i][0]
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        window.location.href = markers[i][3];
      }
    })(marker, i));
  }

  // Zoom so all pins are in view
  map.fitBounds(bounds);
}

有人明白为什么没有调用initMap 函数吗?

【问题讨论】:

  • 你不能在脚本src中添加角度变量
  • ok @sachilaranawaka,我怎样才能运行这个函数来启动地图?
  • 在第一个控制台之后调用函数
  • @sachilaranawaka 这调用了该函数,但是当调用var map = new google.maps.Map(document.getElementById('map') 时,未定义Google 的错误.. 有什么想法吗?感谢您的帮助
  • 因为脚本标签不起作用。向脚本添加一个有效的令牌并尝试它

标签: javascript angularjs google-maps-api-3 localhost


【解决方案1】:

改变脚本标签的顺序

<script src="https://maps.googleapis.com/maps/api/js?key={{API_KEY}}&callback=initMap"></script>
<script src="client/services/maps.client.services.map.js"></script>

【讨论】:

  • 我已经尝试过了,但它不起作用。我得到的错误是: maps.client.scripts.map.js:24 Uncaught ReferenceError: google is not defined at initMap (maps.client.scripts.map.js:24) at maps.client.scripts.map.js: 2
猜你喜欢
  • 2012-08-20
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 2013-01-14
  • 2017-01-12
  • 2017-10-09
  • 2013-11-16
  • 2019-08-16
相关资源
最近更新 更多