javascript - Noob question: How to get information if google map is loaded (initialized) -
i new google maps api. took sample manual , trying change way need, here trying do: example 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 not successful following reason: " + status); } }); }
i have changed codeaddress function little , trying call on page load 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 not successful following reason: " + status); } }); } codeaddress("some address");
but give me javascript error "geocoder undefined". how can make script wait until map loaded , run codeaddress function? don't want path address during initialization.
i hope clear thank in advance.
the problem you're calling codeaddress
directly after defining (and hence before initialise()
method runs.
consequently need run later on trigger. quick , dirty way set body's onload
event; wait until resources (including images) have loaded, might not of problem given map image well.
alternatively, js frameworks give convenient methods fire handlers @ various points in page's lifecycle. if you're using 1 of these, may wish investigate options available , pick best one, depends on number of factors.
critically, don't forget must call initialise()
before call codeaddress()
!
Comments
Post a Comment