Search code examples
javascriptgoogle-maps-api-3methodsgoogle-maps-engine

Cannot call method of undefined but alert(method) still working


I've been playing around with this for an hour and it may be something small I'm missing, but I can't seem to get the Google API path method ".lat()" or ".lng()" to work in my function. However if I alert the same method it will show me the lat/lng values just fine. This function is attempting to build the LINESTRING section of the WHERE clause of a Maps Engine query.

queryWhere += "ST_DISTANCE(geometry,ST_GEOMFROMTEXT('LINESTRING(";

    for(x = 0; x <= path.length; x=x+2){

        queryWhere += path[x].lng() + " " + path[x].lat();

        if(!path[path.length - 1] || !path[path.length - 2]){

            queryWhere += ", ";
                }
        }
            queryWhere += ")'))<5000";   

I'm getting back "Uncaught TypeError: Cannot call method 'lng' of undefined", however if I do:

alert(path[x].lng() + " " + path[x].lat());

It's working perfectly fine.


Solution

  • Can only check to last elemnt in array. Index is zero based, so last index is ( length - 1)

    Change to just less than length

    for(x = 0; x < path.length; x=x+2)
    

    You are overshooting the array in your code, so last pass will return undefined for path[x]