Error (Uncaught ReferenceError: google is not defined) in the "Run" in the MAPS API for Autocomplete

1

An error is occurring in the " google.maps.event.addDomListener (window, 'load', initialize) ;" and I can not resolve: '(

function initialize() {
  var mapOptions = {
    center: {lat: -33.8688, lng: 151.2195},
    zoom: 13,
    scrollwheel: false
  };
  var map = new google.maps.Map(document.getElementById('map'),
    mapOptions);

  var input = /** @type {HTMLInputElement} */(
      document.getElementById('pac-input'));

  // Create the autocomplete helper, and associate it with
  // an HTML text input box.
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  var infowindow = new google.maps.InfoWindow();
  var marker = new google.maps.Marker({
    map: map
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
  });

  // Get the full place details when the user selects a place from the
  // list of suggestions.
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    infowindow.close();
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      return;
    }

    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }

    // Set the position of the marker using the place ID and location.
    marker.setPlace(/** @type {!google.maps.Place} */ ({
      placeId: place.place_id,
      location: place.geometry.location
    }));
    marker.setVisible(true);

    infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
        'Place ID: ' + place.place_id + '<br>' +
        place.formatted_address + '</div>');
    infowindow.open(map, marker);
  });
}

// Run the initialize function when the window has finished loading.
google.maps.event.addDomListener(window, 'load', initialize);
    
asked by anonymous 13.01.2018 / 21:49

1 answer

0

You need to load the API plugin:

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=CHAVE_DA_API"></script>

Howyouarestartingthepluginviacodein:

google.maps.event.addDomListener(window,'load',initialize);

Thennoshouldspecifyasyncdeferinthescripttag( see information about async and defer in this response ), getting only:

<script src="https://maps.googleapis.com/maps/api/js?key=CHAVE_DA_API"></script>

OryoucanstartthepluginviacallbackintheURL(thenyouneedtheasyncanddefer):

<scriptasyncdefersrc="https://maps.googleapis.com/maps/api/js?key=CHAVE_DA_API&callback=initialize">
</script>

So in the latter case, you have to delete the line google.maps.event.addDomListener(window, 'load', initialize); which has the same effect as callback .

    
14.01.2018 / 02:03