I am writing a JavaScript application using the Google 3 Javascript API and RequireJS. I wrote a small wrapper for gmaps to get dependencies correctly:
define('gmaps', ['goog!maps,3.9,packages:[geometry],language:de,other_params:sensor=false&channel=...&client=...'],
function(){
return window.google.maps;
});
This works great in most cases, even after you cut the code using the optimizer. However, sometimes I get an error message gmaps.geometry is undefinedin a module with gmapsas a dependency and try to calculate the distance:
define(['gmaps'], function(gmaps) {
return {
...
calcDistance: function(target) {
var position = this.getPosition();
var distance = gmaps.geometry.spherical.computeDistanceBetween(
new gmaps.LatLng(position.latitude, position.longitude),
new gmaps.LatLng(target.latitude, target.longitude)
);
return (distance / 1000).toFixed(2);
}
}
});
This only happens if I try to execute calcDistanceright after the page, and the necessary data is downloaded and only occasionally. I assume this is some problem with asynchronously loading gmaps, but I do not quite understand it. How to define gmaps, but gmaps.geometry will be undefined? Is there any way to fix this?