I am trying to create a function that will create a new marker. I need to handle some properties of a new marker in a callback. The problem is that marker instantly created and can be used to call a callback, but some properties are not yet available.
If I wait two seconds before trying to access the properties, it works just fine - it makes me think that the object still generates itself asynchronously after creation.
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Simple markers</title> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style> </head> <body> <div id="map"></div> <script> function initMap() { var latLng = new google.maps.LatLng(-25.363, 131.044); var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: latLng }); function placeMarker(map, latLng, callback, callback2){ var marker = new google.maps.Marker({ position: latLng, map: map }); callback(marker); callback2(marker); } placeMarker(map, latLng, function(marker){ setTimeout( function(){ console.log(marker.Xg.Oa) }, 2000); }, function(marker){ console.log(marker.Xg.Oa); }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script> </body> </html>
In this example, the callback:
setTimeout( function(){ console.log(marker.Xg.Oa) }, 2000);
gives the correct answer. But a callback that does not wait shows an undefined error:
function(marker){ console.log(marker.Xg.Oa); }
I am using the Javascript API for Google Maps here, and using google.maps is not obvious. I want to pass the whole object to a callback, but I need to make sure that the latLng information ( marker.Xg.Oa ) exists before it is called. How can I make sure it is before calling the callback?
source share