How can google.maps.geometry be undefined?

2019-06-17 14:48发布

问题:

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?

回答1:

It seems you are not loading the correct library. Just append &libraries=geometry in the library url.

Check this google.maps.geometry.spherical error



回答2:

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;
});


回答3:

I know this is an old question, but in my situation I see that geometry libraries is not available at the initialization. I don't know why. But it became defined after some time. So I resolve the problem using a wait function.

setTimeout(waitForGeometryLibraries, 250);  

function waitForGeometryLibraries(){
    if(typeof google.maps.geometry !== "undefined"){
     // code using geometry library
    }
    else{
        setTimeout(waitForGeometryLibraries, 250);
    }
}