Reputation: 838
I have the following function in the <head>
of a webpage:
<script type="text/javascript">
$(document).ready(function(){
function googmap(){
var marker;
var circle;
var map;
var bounds = new google.maps.LatLngBounds();
var latit = 5;
var longi = 6;
var search_range = 2;
map = new google.maps.Map(document.getElementById('map'), {
centre: new google.maps.LatLng(latit, longi),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 6
});
marker = new google.maps.Marker({
position: new google.maps.LatLng(latit, longi),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(latit);
infowindow.open(map, marker);
}
})(marker, i));
}
});
</script>
I call this function using:
<body onLoad="googmap()">
However in the javascript console it is telling me that the function googmap()
is not defined. Im sure this issue is to do with scope, etc or the way ive defined the function is wrong, but im very new to JavaScript so I cant troubleshoot it myself - any help would be gratefully received!
Upvotes: 1
Views: 45
Reputation: 1309
You are right when you say that googmap is not defined due to scope. Since the function is created inside an anonymous function:
$(document).ready(function(){
it doesn't exist outside it. Add googmap(); to the end of the anonymous function.
Upvotes: 0
Reputation: 485
You don't need to call "onLoad='googmap()'" here because you already do the function in jquery document.ready.
All you need to do here is change the script in: (leave out the rule 'function googmap() {' and the matching closing '}')
$(document).ready(function(){
var marker;
var circle;
var map;
var bounds = new google.maps.LatLngBounds();
var latit = 5;
var longi = 6;
var search_range = 2;
map = new google.maps.Map(document.getElementById('map'), {
centre: new google.maps.LatLng(latit, longi),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 6
});
marker = new google.maps.Marker({
position: new google.maps.LatLng(latit, longi),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(latit);
infowindow.open(map, marker);
}
})(marker, i));
});
</script>
Upvotes: 1