Noob question: How to get information if google map is loaded (initialized)
I am new with google maps api. I took some sample from the manual and trying to change it the way I need, so here is the what I am trying to do: This is the example from google maps manual
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng( 40.714353, -74.005973);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
I have changed codeAddress fun开发者_开发问答ction a little and trying to call it on page load like this:
function codeAddress(address) {
//var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
codeAddress("Some Address");
But it give me a javascript error "geocoder is undefined". How can I make the script wait until the map is loaded and then run the codeAddress function? I don't want to path my address during initialization.
I hope this is clear Thank you in advance.
The problem is that you're calling codeAddress
directly after defining it (and hence this is before the initialise()
method runs.
Consequently you need to run this later on some trigger. A quick and dirty way to do this is to set this as the body's onload
event; this will wait until all resources (including images) have fully loaded, but that might not be too much of a problem given that the map is an image as well.
Alternatively, most JS frameworks will give you very convenient methods to fire your handlers at various points in the page's lifecycle. If you're using one of these, you may wish to investigate the options available to you and pick the best one, which depends on a number of factors.
Critically, don't forget that you must call initialise()
before you call codeAddress()
!
精彩评论