谷歌地图Javascript API加载不正确

Google Maps Javascript API not loading correctly

本文关键字:不正确 加载 API Javascript 谷歌地图      更新时间:2023-09-26

我正在尝试将Google Maps API加载到一个网页中,该网页的主体底部带有<script>标签,上面引用了#map元素。

获取错误警报:"此页面无法显示Google Maps元素。提供的Google API密钥无效或未授权此网站使用它。错误代码:InvalidKeyOrUnauthorizedURLMapError"

我的API密钥是绝对正确的;我已经检查了很多次了。

我已选择接受以下推荐人的请求
*.mywebsite.com/*
*.mywebsite.com*
www.mywebsite.com/*
www.mywebsite.com/test//这是我试图加载地图的url。

我尝试过不使用API密钥引用,也不使用Init回调和映射间歇性加载。有时它会加载(大约20%的时间),有时不会,我会得到以下控制台日志-ReferenceError:google没有定义;

<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script src="/js/map.js"></script>

我的map.js文件包含地图配置

var map;
var mapLatLng = {lat: 13.778182, lng: -0.23676};
var mapStyle = [maps style options] // https://snazzymaps.com/style/38/shades-of-grey
var mapMarker = '/img/marker.png';
function initMap() {
  var styledMap = new google.maps.StyledMapType(mapStyle,
  {name: "Styled Map"});
  var mapOptions = {
    center: mapLatLng,
    zoom: 10,
    scrollwheel: false,
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    mapTypeControlOptions: {
    mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
  }
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker = new google.maps.Marker({
  position: mapLatLng,
  map: map,
  title: 'Hello World!',
  icon: mapMarker
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
google.maps.event.addDomListener(window, 'load', initMap);

您将GMap脚本调用为async defer,因此您不确定该脚本是否会在map.js之前下载并执行。而您的map.js[/em>脚本调用GMap API。

是否可以在没有async defer属性的情况下先进行测试。如果可以的话,只需在initMap函数中移动所有初始化代码,它就会起作用:

function initMap() {
   var map = new google.maps.Map(document.getElementById('map'), mapOptions);
   var marker = new google.maps.Marker({
      position: mapLatLng,
      map: map,
      title: 'Hello World!',
      icon: mapMarker
    });
   //Associate the styled map with the MapTypeId and set it to display.
   map.mapTypes.set('map_style', styledMap);
   map.setMapTypeId('map_style');
   var styledMap = new google.maps.StyledMapType(mapStyle, {name: "Styled Map"});
   var mapOptions = {
        center: mapLatLng,
        zoom: 10,
        scrollwheel: false,
        navigationControl: false,
        mapTypeControl: false,
        scaleControl: false,
        mapTypeControlOptions: {
        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
      }
   };
}