-2

As explained in this question, I have added &callback=initialize to the script that loads the Google Maps API:

<script src="https://maps.googleapis.com/maps/api/js?key=XXXX&amp;callback=initialize&amp;region=it&amp;libraries=places" async defer></script>

The map loads, but directions don't anymore and I get the following errors:

Uncaught ReferenceError: google is not defined
    at map.html:15

Uncaught (in promise) TypeError: Cannot read property 'push' of undefined
    at initialize (map.html:60)
    at js?key=XXXX&callback=initialize&region=it&libraries=places:130

What am I doing wrong?

This is the function (I have changed the GPS coords and removed info from label/address for privacy):

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var mkArray=[];

function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myLatlng = new google.maps.LatLng(41.389835,12.413704);

var mapOptions = {
    zoom:16,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: myLatlng,
    styles: [
        {
            featureType: "poi.business",
            elementType: "labels",
            stylers: [
                    { visibility: "off" }
            ]
        }
    ]
  }

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));

var input = document.getElementById('start');
var options = {
    types: ['geocode'],
    componentRestrictions: {country: 'it'},
    rankBy: google.maps.places.RankBy.DISTANCE
};
var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(41.76, 12.33),
    new google.maps.LatLng(42.00, 12.64)
);
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.setBounds(bounds);

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'XXXXX'
});
mkArray.push(marker);
}

function calcRoute(callback) {
    var start = document.getElementById('start').value;
    var end = "Address, Rome";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

        // If a callback was passed, run it
        if(typeof callback === "function") {
            callback();
        }

      }
    });
    for (var i = 0, j = mkArray.length; i < j; i++) 
      mkArray[i].setMap(null);
}

google.maps.event.addDomListener(window, 'load', initialize);
MultiformeIngegno
  • 6,959
  • 15
  • 60
  • 119

1 Answers1

1

You're trying to use google object before loading it:

var directionsService = new google.maps.DirectionsService()

You need to wait for your callback initialize to be executed to use google object, so my best advise is to do something like this (as you already did for directionsDisplay):

var directionService;

function initialize() {
   directionsService = new google.maps.DirectionsService();

   // other code here
}

And on your last line what are you trying to do?

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

You're making 2 errors here:

  1. Still trying to use google before your callback gets called
  2. You're trying to register the same function for both GMaps API callback and window load event. This won't work because of first point, but even if it did you would end up executing initialize twice and I don't think it's what you want.
dcop
  • 26
  • 1
  • 3