TrapezeArtist
TrapezeArtist

Reputation: 907

Google Maps API - "google is not defined"

This is driving me mad. I have a page which loads a second page containing a google map. The second page works perfectly on its own but it just shows a blank space when it is opened within the first page.

Javscript console gives the message "ReferenceError: google is not defined".

The first (main) page uses this script to load the map page:

$(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);
});
});

Then the second page uses this script for the google maps.

      // 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);
        }

      });
    }

Things I've tried already:

  1. I've tried putting a text file in the .load() of the first script to make sure that is working correctly. It is.

  2. I've taken care to ensure that all references to other files are relative to the root ie "/includes/php-to-xml.php".

  3. I already had to fiddle around with the order of different parts of the script to make it work at all. I've tried putting all the javascript inside the initMap function but that didn't help either.

  4. I tried wrapping the entire content of the script in window.onload = function() { but that broke it completely.

  5. Originally I was loading the API with async defer and a callback to the initMap function. I've now dropped all that and use body onload="initMap()" instead. The link to the API and a couple of other external scripts (on my server) are all in the body.

One final point to clarify: I am running all this on a test server on my own machine.

I bet it's something simple (it always is!) but I can't see what.

EDIT geocodezip asked for a minimal, complete code. The main page (in minimal form ie irrelevant stuff removed) is

<!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>

The map page is

<!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>

The automatic SO system has asked for an edit to explain why my question is not answered by other posts with similar titles. I've tried numerous similar posts and taken several solutions where they seemed relevant but none of them worked.

SECOND EDIT. Further investigation seems to suggest that the problem is a conflict between Jquery and Google Maps, and not a problem with my script in the maps page Therefore to avoid this question getting any longer, I've opened a new question here: https://stackoverflow.com/questions/43394074/conflict-between-jquery-and-google-maps-api

Upvotes: 2

Views: 7208

Answers (2)

Wisdom Jere
Wisdom Jere

Reputation: 76

I had the same problem but after deep investigation in the console I discovered this "UNKNOWN_ERROR",OVER_QUERY_LIMIT:"OVER_QUERY_LIMIT",REQUEST_DENIED:"REQUEST_DENIED" To fix it i had to activate billing in cloud console.

Upvotes: 0

Abdul Shaikh
Abdul Shaikh

Reputation: 129

So to me it looks like the problem is in this line of code:

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

this does not look like a valid format for the google maps API link. I would recommend using the simple map example from the google maps page first. I will link it below here:

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

Also one thing that I typically do is put my reference to the google maps api at the bottom of my html. Try that first and that might solve your issue.

Upvotes: 0

Related Questions