I have the following code for google maps. The purpose of this code is to display a map with a marker in the middle. The marker is draggable, and when it is dropped, I need it to give the current Lat/Long where the marker was dropped. The event doesn’t always fire. In chrome, if I just let the code run, it doesn’t work. But, if I slow it down by debugging and putting a stop on the code that attaches the event, then let it continue, it works. It seems like there is a race condition somewhere, but I have no idea where. Can someone please take a look and see if you come up with something.
function initialize() {
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var canvas = document.getElementById("MapCanvas");
var map = new google.maps.Map(canvas, myOptions);
// Try W3C Geolocation (Preferred)
if (navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
marker = new google.maps.Marker({
position: initialLocation,
draggable: true,
map: map,
title: "You are here"
});
}, function () {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
map.setCenter(initialLocation);
marker = new google.maps.Marker({
position: initialLocation,
draggable: true,
map: map,
title: "You are here"
});
}, function () {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
google.maps.event.addListener(marker, 'dragend', function () {
$("#txtLat").val(marker.position.Ia);
$("#txtLong").val(marker.position.Ja);
});
}
I haven’t tested this, but it looks like
markeris being initialized within one of thegetCurrentPositionfunctions. I’m guessing both of these functions are asynchronous, which is why they take a callback function. However, you’re trying to attach the listener function tomarkersynchronously – so under normal conditions, you’re probably trying to attach the listener tomarkerbeforemarkeris initialized. (Also, I don’t see avarstatement formarker, so unless you left that out,markeris in the global namespace – probably not what you want).The way to fix this is to attach the listener in the callback function, after
markerhas been initialized. Since the callback looks like it’s the same for the W3C Geolocation API and the Gears API, you might want to put the whole thing into a single function: