Skip to content

Instantly share code, notes, and snippets.

@swalberg
Last active August 29, 2015 14:11
Show Gist options
  • Save swalberg/3a32677b4a723a7ca9e6 to your computer and use it in GitHub Desktop.
Save swalberg/3a32677b4a723a7ca9e6 to your computer and use it in GitHub Desktop.
Is it `this` or callbacks tripping me up?
asked to geolocate 570 Renfrew St, Winnipeg, MB 0 index.js:12
asked to geolocate 600 Renfrew St, Winnipeg, MB 1 index.js:16
in callback Address {textAddress: "600 Renfrew St, Winnipeg, MB", foo: 1, latlon: null, mapObj: null, geolocate: function}
geocode complete [Object]
placing a marker at 600 Renfrew St, Winnipeg, MB hf {k: 49.8609077, D: -97.19679180000003, toString: function, j: function, equals: function…}
in callback Address {textAddress: "600 Renfrew St, Winnipeg, MB", foo: "seen", latlon: hf, mapObj: Mj, geolocate: function}
geocode complete [Object]
placing a marker at 600 Renfrew St, Winnipeg, MB hf {k: 49.8602556, D: -97.19661889999998, toString: function, j: function, equals: function…}
addresses
[Address
foo: 0 latlon: nullmapObj: nulltextAddress: "570 Renfrew St, Winnipeg, MB"__proto__: Address,
Address foo: "seen" latlon: hfmapObj: MjtextAddress: "600 Renfrew St, Winnipeg, MB"__proto__: Address]
var geocoder;
function Address(textAddress) {
this.textAddress = textAddress;
this.foo = "";
this.latlon = null;
this.mapObj = null;
}
Address.prototype.geolocate = function(afterGeo) {
console.log("asked to geolocate", this.textAddress, this.foo);
addressObject = this;
geocoder.geocode( {'address': this.textAddress }, function(results, status) {
console.log("in callback", addressObject);
addressObject.foo = "seen";
if (status == google.maps.GeocoderStatus.OK) {
console.log("geocode complete", results);
addressObject.latlon = results[0].geometry.location
addressObject.mapObj = afterGeo(addressObject);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var a = [ "570 Renfrew St, Winnipeg, MB", "600 Renfrew St, Winnipeg, MB"];
var addresses = [];
for (var i=0; i < a.length; i++) {
addresses[i] = new Address(a[i]);
addresses[i].foo = i;
}
function initialize() {
// map stuff removed
geocoder = new google.maps.Geocoder();
for (var i=0; i < addresses.length; i++) {
addresses[i].geolocate(function(obj) {
console.log("placing a marker at", obj.textAddress, obj.latlon);
// This doesn't matter to the example, but it does place the markers in the right spot.
var marker = new google.maps.Marker({
map: map,
position: obj.latlon,
title: obj.textAddress
});
return marker;
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment