javascript - 谷歌地图 API - "google is not defined"

标签 javascript google-maps

这让我抓狂。我有一个页面加载包含谷歌地图的第二页。第二页本身可以完美运行,但在第一页中打开时仅显示空白。

Javscript 控制台显示消息“ReferenceError:google 未定义”。

第一个(主)页面使用此脚本加载 map 页面:

$(document).ready(function(){
$("#maplink").click(function(){
 var txt = $("#mapspace").is(':visible') ? 'See location map' : 'Hide location map';
 $("#maplink").text(txt);
 $("#mapspace").slideToggle(2000, function() {
    $("#mapspace").load("/includes/map_hotel.php?hid=<?php echo $row_hotel['hid'] ?>");
});
$('html, body').animate({
    scrollTop: $("#maplink").offset().top
}, 2000);
});
});

然后第二页将此脚本用于谷歌地图。

      // global "map" variable
      var map = null;

// InfoBox
 var boxText = document.createElement("div");
        boxText.style.cssText = "border:1px solid #3498db;border-radius:5px;margin-top:8px;background:white;padding:5px;";

        var ibOptions = {
         content: boxText
        ,closeBoxURL: ""
        ,disableAutoPan: false
        ,enableEventPropagation: true
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(15, -50)
        ,boxStyle: { 
         width: "240px"
         }
        };

// global "infobox" variable
  var ib = new InfoBox(ibOptions);

function createMarker(latlng, html) {
    var contentString = html;

    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: "/images/hotel_grey_icon.gif",
        zIndex: 9998
        });

    google.maps.event.addListener(marker, 'mouseover', function() {
        boxText.innerHTML = contentString;
        ib.open(map, marker);
        });
      google.maps.event.addListener(map, 'click', function() {
        ib.close(map, marker);
        });
}

function initMap() {
      var lat = <?php echo $row_hotel['latitude'] ?>;
      var lng = <?php echo $row_hotel['longitude'] ?>;
      var zoom = 10;
  var thisLatlng = new google.maps.LatLng(lat, lng);
  var mapOptions = {
center: thisLatlng,
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
   streetViewControl: true,
   scaleControl: true,
   zoomControl: true
   }

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  var hotelContentString = '<div class="thishotel"><?php echo $row_hotel['hotel_name'] ?></div>';

  var hotelmarker = new google.maps.Marker({
      position: thisLatlng,
      map: map,
      icon: "/images/hotel_icon.gif",
      zIndex: 9999
  });

// Infobox for this hotel
        var hibOptions = {
         content: boxText
        ,closeBoxURL: ""
        ,disableAutoPan: false
        ,enableEventPropagation: true
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(-70, -75)
        ,boxStyle: { 
         width: "140px"
         }
        };

  var hib = new InfoBox(hibOptions);

      google.maps.event.addListener(hotelmarker, 'mouseover', function() {
        boxText.innerHTML = hotelContentString;
        hib.open(map, hotelmarker);
        });
      google.maps.event.addListener(map, 'click', function() {
        hib.close(map, hotelmarker);
        });

var style_nopoi = [{"featureType": "poi", "stylers": [{"visibility": "off"}]}]; // Styles, removes points-of-interest. Lots of other possibilities.
map.setOptions({styles: style_nopoi});  // Applies the style to the map

var loadcnt = 0;
      google.maps.event.addListener(map, 'tilesloaded', function() {
        if (loadcnt==0) {
        map.setCenter(thisLatlng); // Seems to fix random centring problem on mobiles
        loadcnt=loadcnt+1;
        }
        });

      downloadUrl("/includes/php-to-xml.php?iso=<?php echo $row_hotel['countryisocode'] ?>", function(doc) {
        var xmlDoc = xmlParse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {

          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new google.maps.LatLng(lat,lng);
          var html=markers[i].getAttribute("html");

          createMarker(point, html);
        }

      });
    }

我已经尝试过的事情:

  1. 我尝试将文本文件放入第一个脚本的 .load() 中,以确保其正常工作。是的。

  2. 我已注意确保对其他文件的所有引用都相对于根目录,即“/includes/php-to-xml.php”。

  3. 我已经不得不调整脚本不同部分的顺序才能使其正常工作。我尝试将所有 JavaScript 放入 initMap 函数中,但这也没有帮助。

  4. 我尝试将脚本的全部内容包装在 window.onload = function() { 中,但这完全破坏了它。

  5. 最初,我使用异步延迟和 initMap 函数的回调来加载 API。我现在已经放弃了所有这些并使用 body onload="initMap()"代替。 API 的链接和其他几个外部脚本(在我的服务器上)都在正文中。

最后需要澄清的一点是:我正在我自己的计算机上的测试服务器上运行所有这些。

我敢打赌这很简单(总是如此!)但我看不出是什么。

编辑 geocodezip 要求一个最小的、完整的代码。主页(以最小形式,即删除不相关的内容)是

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/css/lightgallery.css" />
</head>

<body>

<!-- Header -->
<header id="header">
<div class="logo"><a href="index.html">BEST Small Hotels</a></div>
<a href="#menu">Menu</a>
</header>

<!-- Banner -->
<section id="banner" style="background-image: url(<?php echo '/images/'.$row_hotel['countryisocode'].'/'.$row_hotel['hid'].'/'.$row_hotel['mainphoto']; ?>)">
<div class="inner">
<header>
<h1><?php echo $row_hotel['hotel_name'] ?></h1>
<h2><?php echo $row_hotel['summary'] ?></h2>
</header>
<a href="#main" class="more">Learn More</a>
</div>

<!-- Main -->
<div id="main">

<!-- Map Section -->
<section class="wrapper style1" style="padding:0">
<div class="inner">
<!-- 2 Columns -->
<div class="flex flex-2">
<div id="mapspace"></div>
</div>
</div>
</section>

</div>

<?php include('footer.php'); ?>

        <!-- Scripts -->
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <script src="/js/jquery.scrolly.min.js"></script>
            <script src="/js/jquery.scrollex.min.js"></script>
            <script src="/js/skel.min.js"></script>
            <script src="/js/util.js"></script>
            <script src="/js/main.js"></script>
            <script src="/js/picker.js"></script>
            <script src="/js/lightgallery.min.js"></script>
            <script src="/js/lg-thumbnail.min.js"></script>
            <script src="/js/tooltip.js"></script>

            <link type="text/css" rel="stylesheet" href="/css/picker.css">

<script>
$(document).ready(function(){
    $("#maplink").click(function(){
     var txt = $("#mapspace").is(':visible') ? 'See location map' : 'Hide location map';
     $("#maplink").text(txt);
     $("#mapspace").slideToggle(2000, function() {
        $("#mapspace").load("/includes/map_hotel.php?hid=<?php echo $row_hotel['hid'] ?>");
    });
    $('html, body').animate({
        scrollTop: $("#maplink").offset().top
    }, 2000);
    });
});
</script>
</body>
</html>

map 页面是

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" />
<style>
html, body{height:100%;margin:0;padding:0}
#map_canvas{height:100%}
.info{font-family:Arial, Helvetica, sans-serif}
.info h1{font-size:1.2em;font-weight:bold;color:#3498db;line-height:normal;margin-bottom:.1em}
.thishotel{font-size:1.2em;font-weight:bold;color:#3498db;text-align:center}
</style>
</head>

<body> 
<div id="map_canvas"></div>

<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyAVWhJbk79iVcXRDoaG75l7glsdS2hYRyo"></script>
<script type="text/javascript" src="/js/downloadxml.js"></script>
<script type="text/javascript" src="/js/infobox.js"></script>
<script type="text/javascript"> 
google.maps.event.addDomListener(window,'load',initMap);
     // global "map" variable
      var map = null;

// InfoBox
 var boxText = document.createElement("div");
        boxText.style.cssText = "border:1px solid #3498db;border-radius:5px;margin-top:8px;background:white;padding:5px;";

        var ibOptions = {
         content: boxText
        ,closeBoxURL: ""
        ,disableAutoPan: false
        ,enableEventPropagation: true
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(15, -50)
        ,boxStyle: { 
         width: "240px"
         }
        };

// global "infobox" variable
  var ib = new InfoBox(ibOptions);

function createMarker(latlng, html) {
    var contentString = html;

    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: "/images/hotel_grey_icon.gif",
        zIndex: 9998
        });

    google.maps.event.addListener(marker, 'mouseover', function() {
        boxText.innerHTML = contentString;
        ib.open(map, marker);
        });
      google.maps.event.addListener(map, 'click', function() {
        ib.close(map, marker);
        });
}

function initMap() {
      var lat = <?php echo $row_hotel['latitude'] ?>;
      var lng = <?php echo $row_hotel['longitude'] ?>;
      var zoom = 10;
  var thisLatlng = new google.maps.LatLng(lat, lng);
  var mapOptions = {
center: thisLatlng,
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
   streetViewControl: true,
   scaleControl: true,
   zoomControl: true
   }

  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  var hotelContentString = '<div class="thishotel"><?php echo $row_hotel['hotel_name'] ?></div>';

  var hotelmarker = new google.maps.Marker({
      position: thisLatlng,
      map: map,
      icon: "/images/hotel_icon.gif",
      zIndex: 9999
  });

// Infobox for this hotel
        var hibOptions = {
         content: boxText
        ,closeBoxURL: ""
        ,disableAutoPan: false
        ,enableEventPropagation: true
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(-70, -75)
        ,boxStyle: { 
         width: "140px"
         }
        };

  var hib = new InfoBox(hibOptions);

      google.maps.event.addListener(hotelmarker, 'mouseover', function() {
        boxText.innerHTML = hotelContentString;
        hib.open(map, hotelmarker);
        });
      google.maps.event.addListener(map, 'click', function() {
        hib.close(map, hotelmarker);
        });

var style_nopoi = [{"featureType": "poi", "stylers": [{"visibility": "off"}]}]; // Styles, removes points-of-interest. Lots of other possibilities.
map.setOptions({styles: style_nopoi});  // Applies the style to the map

var loadcnt = 0;
      google.maps.event.addListener(map, 'tilesloaded', function() {
        if (loadcnt==0) {
        map.setCenter(thisLatlng); // Seems to fix random centring problem on mobiles
        loadcnt=loadcnt+1;
        }
        });

      downloadUrl("/includes/php-to-xml.php?iso=<?php echo $row_hotel['countryisocode'] ?>", function(doc) {
        var xmlDoc = xmlParse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {

          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new google.maps.LatLng(lat,lng);
          var html=markers[i].getAttribute("html");

          createMarker(point, html);
        }

      });
    }
</script>
</body>
</html>

自动 SO 系统要求进行编辑,以解释为什么其他具有类似标题的帖子没有回答我的问题。我尝试过许多类似的帖子,并采取了几种看似相关的解决方案,但没有一个有效。

第二次编辑。进一步调查似乎表明问题是 Jquery 和 Google map 之间的冲突,而不是 map 页面中我的脚本的问题因此,为了避免这个问题变得更长,我在这里提出了一个新问题:https://stackoverflow.com/questions/43394074/conflict-between-jquery-and-google-maps-api

最佳答案

所以对我来说问题似乎出在这行代码中:

<script src="//maps.googleapis.com/maps/api/js? 
 key=AIzaSyAVWhJbk79iVcXRDoaG75l7glsdS2hYRyo"></script>

这看起来不像 google map API 链接的有效格式。我建议首先使用谷歌地图页面中的简单 map 示例。我将在下面链接它:

https://developers.google.com/maps/documentation/javascript/examples/map-simple

我通常做的一件事是将我对 google map api 的引用放在 html 的底部。首先尝试一下,这可能会解决您的问题。

关于javascript - 谷歌地图 API - "google is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366289/

相关文章:

javascript - 在 react Hook 中,我如何将新创建的对象传递给状态对象?

javascript - flowtype:在 redux 操作中使用常量时为 "object literal could not decide which case to select"

javascript - 使用 formData.set 更改名称

javascript - 获取 Google Maps API map 的宽度(以公里为单位)

javascript - height=100% 不渲染 google maps api

google-maps - 根据您所处的缩放级别显示谷歌地图标记

javascript - 如何在 Javascript 命名空间脚本中创建函数数组

javascript - 通过 webpack 包含 socket.io 时获取 `Uncaught ReferenceError: io is not defined`

javascript - 为 Google map 方向服务循环多个起点

java - 如果作为现有 Android 源代码导入,Facebook SDK 会导致 google-play-services-lib 崩溃