Google Maps Issue Cannot call method 'apply' of undefined?
I have searched all over google for a solution however this seems a new开发者_Go百科 one? I am trying to implement google maps API on a site however I keep getting the following error:
Uncaught TypeError: Cannot call method 'apply' of 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);
});
In this line
google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));
You're calling the function addMarker instead of passing it as a function reference. Therefore, addMarker is getting executed before map is defined. Try changing that line to:
google.maps.event.addDomListener(map, 'tilesloaded', function() {addMarker(location)});
The problem is you're invoking the function addMarker
which you should be supplying a callback. Change your call to the following
google.maps.event.addDomListener(map, 'tilesloaded', function() { addMarker(location) });
Right now you're instead directly invoking addMarker
which returns no value. This means you're effectively passing undefined
to the API and the google library is hitting the error attempting to invoke your callback
精彩评论