最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google Maps: Uncaught ReferenceError: google is not defined - Stack Overflow

programmeradmin1浏览0评论

I am receiving this error when I try to load an HTML page with my map:

Uncaught ReferenceError: google is not defined

I thought it was the order in which I was loading the Google maps API, but I have it at the beginning.

My HTML looks like this:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href=".3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJT$
    <script src=".3.1/jquery.min.js"></script>
    <script src=";callback=initMap"
    async defer></script>
    <script src="mapCode.js"></script>


    <title>Adventure Map</title>

</head>
<body>
<select id="type" onchange="filterMarkers(this.value);">
  <option value="">All Markers</option>
  <option value="backpacking">Backpacking</option>
  <option value="hiking">Hiking</option>
  <option value="offRoad">Off Road</option>
</select>

<div id="map-canvas" style="width: 100%; height: 600px"></div>

</body>

The mapCode.js that my html code calls looks like this. DO I have thing in the wrong order, is it not loading the google API in time before loading the map?:

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
  content: ''
});
var markerCluster;

// Our markers
markers1 = [
  ['0', 'Tanner Trail Grand Canyon', 36.0326, -111.8525, 'backpacking'],
  ['1', 'Yosemite Snow Shoe Badger Pass', 37.6648, -119.6634, 'backpacking'],
  ['2', 'Kayak Camping Catalina Island', 33.3504, -118.3282, 'backpacking'],
  ['3', 'Mini Trans Catalina Trail', 33.3403, -118.3262, 'backpacking']
];

/**
 * Function to init map
 */

function initialize() {
  var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
  var mapOptions = {
    zoom: 3,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markers1.length; i++) {
    addMarker(markers1[i]);
  }
  markerCluster = new MarkerClusterer(map, gmarkers1, {
    imagePath: ''
  });
}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
  var category = marker[4];
  var title = marker[1];
  var pos = new google.maps.LatLng(marker[2], marker[3]);
  var content = marker[1];

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    category: category,
    map: map
  });

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      //map.setZoom(15);
    }
  })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function(category) {
  var newmarkers = [];
  for (i = 0; i < markers1.length; i++) {
    marker = gmarkers1[i];
    // If is same category or category not picked
    if (marker.category == category || category.length === 0) {
      marker.setVisible(true);
      newmarkers.push(marker);
    }
    // Categories don't match 
    else {
      marker.setVisible(false);
    }
  }
  markerCluster.clearMarkers();
  markerCluster.addMarkers(newmarkers);
}
google.maps.event.addDomListener(window, "load", initialize);

I am receiving this error when I try to load an HTML page with my map:

Uncaught ReferenceError: google is not defined

I thought it was the order in which I was loading the Google maps API, but I have it at the beginning.

My HTML looks like this:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn./bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJT$
    <script src="https://ajax.googleapis./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maps.googleapis./maps/api/js?key=MYKEY&callback=initMap"
    async defer></script>
    <script src="mapCode.js"></script>


    <title>Adventure Map</title>

</head>
<body>
<select id="type" onchange="filterMarkers(this.value);">
  <option value="">All Markers</option>
  <option value="backpacking">Backpacking</option>
  <option value="hiking">Hiking</option>
  <option value="offRoad">Off Road</option>
</select>

<div id="map-canvas" style="width: 100%; height: 600px"></div>

</body>

The mapCode.js that my html code calls looks like this. DO I have thing in the wrong order, is it not loading the google API in time before loading the map?:

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
  content: ''
});
var markerCluster;

// Our markers
markers1 = [
  ['0', 'Tanner Trail Grand Canyon', 36.0326, -111.8525, 'backpacking'],
  ['1', 'Yosemite Snow Shoe Badger Pass', 37.6648, -119.6634, 'backpacking'],
  ['2', 'Kayak Camping Catalina Island', 33.3504, -118.3282, 'backpacking'],
  ['3', 'Mini Trans Catalina Trail', 33.3403, -118.3262, 'backpacking']
];

/**
 * Function to init map
 */

function initialize() {
  var center = new google.maps.LatLng(52.4357808, 4.991315699999973);
  var mapOptions = {
    zoom: 3,
    center: center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  for (i = 0; i < markers1.length; i++) {
    addMarker(markers1[i]);
  }
  markerCluster = new MarkerClusterer(map, gmarkers1, {
    imagePath: 'https://cdn.rawgit./googlemaps/v3-utility-library/master/markerclustererplus/images/m'
  });
}

/**
 * Function to add marker to map
 */

function addMarker(marker) {
  var category = marker[4];
  var title = marker[1];
  var pos = new google.maps.LatLng(marker[2], marker[3]);
  var content = marker[1];

  marker1 = new google.maps.Marker({
    title: title,
    position: pos,
    category: category,
    map: map
  });

  gmarkers1.push(marker1);

  // Marker click listener
  google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
    return function() {
      console.log('Gmarker 1 gets pushed');
      infowindow.setContent(content);
      infowindow.open(map, marker1);
      map.panTo(this.getPosition());
      //map.setZoom(15);
    }
  })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function(category) {
  var newmarkers = [];
  for (i = 0; i < markers1.length; i++) {
    marker = gmarkers1[i];
    // If is same category or category not picked
    if (marker.category == category || category.length === 0) {
      marker.setVisible(true);
      newmarkers.push(marker);
    }
    // Categories don't match 
    else {
      marker.setVisible(false);
    }
  }
  markerCluster.clearMarkers();
  markerCluster.addMarkers(newmarkers);
}
google.maps.event.addDomListener(window, "load", initialize);
Share Improve this question asked Mar 9, 2019 at 23:43 Ten Digit GridTen Digit Grid 2,6397 gold badges37 silver badges57 bronze badges 2
  • 1 I think one error is that you need to change <script src="https://maps.googleapis./maps/api/js?key=MYKEY&callback=initMap" async defer></script> into <script src="https://maps.googleapis./maps/api/js?key=MYKEY&callback=initialize" async defer></script> you have no initMap function. – Nils Kähler Commented Mar 9, 2019 at 23:52
  • 1 That fixed it to get my map to load. If you make an answer I can mark it correct. It did lead to another error in my js now: google is not defined at mapCode.js 3 – Ten Digit Grid Commented Mar 10, 2019 at 0:01
Add a ment  | 

5 Answers 5

Reset to default 8

I think one error is that you need to change

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

into

<script src="https://maps.googleapis./maps/api/js?key=MYKEY&callback=initialize" async defer></script> 

you have no initMap function, but i assume you want to call initialize().

See https://medium./@nikjohn/speed-up-google-maps-and-everything-else-with-async-defer-7b9814efb2b.

The problem is that your js isn't being loaded asynchronously so its executing before the Google maps script is done being processed.

You need to include a callback function that google can call when its done loading.

<script src="https://maps.googleapis./maps/api/js?callback=initMap" async defer></script>

Embarrassingly enough I just straight up forgot to load the Google Maps script in my index.html:

<script src="https://maps.googleapis./maps/api/js?key={KEY}"></script>

Try reloading the cache of your browser with SHIFT+refresh.

I had this problem because I loaded the google map library after my script, but when I moved it to the top the problem persisted, then I reload the cache of my browser and it worked, I know it's silly but that happened to me.

I got this error shown as I mistakenly exchanged the variable names lat and lng. This is unrelated to any inclusion errors but 'only' a fault in the script.

发布评论

评论列表(0)

  1. 暂无评论