Search code examples
encodinggoogle-maps-api-3typeerrorgeopoints

Google Maps API - Geometry Encoding - TypeError: a.lat is not a function


I have a list of GeoPoints in an array with looks like this:

var coordinates = [[50.7, 6.7], [49.5, 7.0], ...]

When I try to use encodePath for minifying the code as explained here, I get the following error:

TypeError: a.lat is not a function

My code looks like this:

google.maps.geometry.encoding.encodePath(coordinates)

Any ideas?


Solution

  • Finally I found the solution! The problem was that encodePath expects a google.maps.LatLng object and not just the GeoPoints.

    Here is a function which turns an array like the one descripted above into an encoded string:

    function encodeLatLngPolygon(array) {
    
    var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
      }
      poly = new google.maps.Polyline(polyOptions);
    
    var path = poly.getPath();
    
    for(var i=0;i<array.length;i++) {
        var xyz = new google.maps.LatLng(parseFloat(array[i][0]).toFixed(2), parseFloat(array[i][1]).toFixed(2));
        path.push(xyz);            
    
    }
    
    var code = google.maps.geometry.encoding.encodePath(path)
    
    return code;
    }
    

    The toFixed reduces the numbers after the decimal point for saving bytes. You can delete or adjust this parameter.