Search code examples
javascriptgoogle-maps-api-3asynchronousrequirejs

How can google.maps.geometry be undefined?


I'm writing a JavaScript application using the Google Maps Javascript API v3 and RequireJS. I wrote a little wrapper for gmaps in order to get the dependencies right:

define('gmaps', ['goog!maps,3.9,packages:[geometry],language:de,other_params:sensor=false&channel=...&client=...'],
function(){
    return window.google.maps;
}); 

This works perfectly fine in most of the cases, even after minifying the code using the optimizer. However, sometimes I get an error saying gmaps.geometry is undefined in a module that has gmaps as a dependency and tries to calculate a 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 calcDistance right after the page and the required data has loaded and only sometimes. I guess this is some problem with the async loading of gmaps, but I don't fully understand it. How can gmaps be defined but gmaps.geometry be undefined? Is there any way to fix this?


Solution

  • packages:[geometry] doesn't seem to work like I thought it would, so geometry wasn't loaded at all. Google seems to internally load geometry at some point, so my code for distance calculation worked in most cases. I fixed the problem by changing the define call of my gmaps module to:

    define('gmaps', ['goog!maps,3.9,language:de,other_params:libraries=geometry&sensor=false&channel=...&client=...'],
    function(){
        return window.google.maps;
    });