Skip to content Skip to sidebar Skip to footer

Define Google Maps Before Using Its Methods

I am following the google maps api documentation: https://developers.google.com/maps/documentation/javascript/customoverlays The define the USGSOverlay, which is a prototype of goo

Solution 1:

If you look at the example, they are not loading the API asynchronously (with "async defer" and callback function), they are loading it synchronously.

To do that change your API include from:

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

To:

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

Then initialize the map when the DOM (and the API) has finished loading with:

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

var map;
CustomImageOverly.prototype = new google.maps.OverlayView();

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8
  });
  var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(62.281819, -150.287132),
    new google.maps.LatLng(62.400471, -150.005608));

  // The photograph is courtesy of the U.S. Geological Survey.
  var srcImage = 'https://developers.google.com/maps/documentation/javascript/';
  srcImage += 'examples/full/images/talkeetna.png';

  overlay = new CustomImageOverly(bounds, srcImage, map);
}

function CustomImageOverly(bounds, image, map) {

  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  this.div_ = null;

  this.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  width: 100% margin: 0;
  padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

Solution 2:

Load your map.js after the googleapis script.

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

Post a Comment for "Define Google Maps Before Using Its Methods"