Google Maps error Can't call the "apply" method from undefined?

I searched all over Google for a solution, but does this seem new? I am trying to implement google map APIs on a site, but I keep getting the following error:

Uncaught TypeError: Unable to call 'apply' method from undefined

My JS is as follows:

var map; function initialize(location) { var mapDiv = document.getElementById('map-canvas'); var latLng; if (location == 0) { latLng = new google.maps.LatLng(52.066356, 1.102388); } else if (location == 1) { latLng = new google.maps.LatLng(52.672492, 1.232196); } else if (location == 2) { latLng = new google.maps.LatLng(52.207607, 0.123017); } map = new google.maps.Map(mapDiv, { center: latLng, zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP }); google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location)); } function addMarker(location) { var latLng; if (location == 0) { latLng = new google.maps.LatLng(52.066703, 1.113573); } else if (location == 1) { latLng = new google.maps.LatLng(52.672492, 1.232196); } else if (location == 2) { latLng = new google.maps.LatLng(52.207607, 0.123017); } var marker = new google.maps.Marker({ position: latLng, map: map }); } $(document).ready(function () { initialize(0); }); 
+7
source share
2 answers

In this line

 google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location)); 

You call the addMarker function instead of passing it as a reference to the function. Therefore, addMarker starts before the map is determined. Try changing this line to:

 google.maps.event.addDomListener(map, 'tilesloaded', function() {addMarker(location)}); 
+28
source

The problem is that you are calling the addMarker function, which you must send a callback to. Change your call to the next

 google.maps.event.addDomListener(map, 'tilesloaded', function() { addMarker(location) }); 

Right now, you are instead calling addMarker , which does not return a value. This means that you are effectively passing undefined to the API, and an error occurs in the google library when trying to call a callback

+6
source

All Articles