Reputation: 5284
Aside from jQuery and Google Maps, I have two scripts included in the head of my page:
<script src="js/map.js" type="text/javascript"></script>
<script src="js/site.js" type="text/javascript"></script>
map.js contains the code to initialize my map and also have the following function to place a marker on it:
function placeMarker(marker){
clearLocations();
var latlng = new google.maps.LatLng(
parseFloat(marker.lat),
parseFloat(marker.lng)
);
var marker = createMarker(latlng);
map.setZoom(14);
var latLng = marker.getPosition();
map.setCenter(latLng);
}
When I call placeMarker
inside $(document).ready()
in site.js, I get the error, 'map is undefined'. However when I call another function in site.js that executes when a button is clicked, placeMarker
runs in its callback without a problem:
$.ajax({
url: 'ajax/json.php',
dataType: 'json',
data: 'search_string='+inpMapSearch+'&country='+Country,
success: function(data) {
console.log(data);
placeMarker(data);
}
});
Does this mean that the placeMarker
function call inside $(document).ready()
is trying to execute before the map is initialized? How can I run placeMarker
after the map is initialized?
=== EDIT ===
As per request here is the code that initializes the map:
google.maps.event.addDomListener(window, 'load', load);
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(18.735693,-70.162651),
zoom: 8,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
}
Upvotes: 3
Views: 7063
Reputation: 25796
Because the window load event fires after the document.ready
. Hence your map is initialized after the document.ready. You could instead wrap your other code in the $(window).load
$(window).load(function(){
your code here
});
Upvotes: 6