Search code examples
c#.netalgorithmgoogle-mapsgis

C# implementation of Google's 'Encoded Polyline Algorithm'


Does anyone have a concise and robust implementation of Google's Encoded Polyline Algorithm in C#?

I essentially want the implementation of this signature:

public string Encode(IEnumerable<Point> points);

Solution

  • Here's the implementation I settled on:

    public static string Encode(IEnumerable<GeoLocation> points)
    {
        var str = new StringBuilder();
    
        var encodeDiff = (Action<int>)(diff => {
            int shifted = diff << 1;
            if (diff < 0)
                shifted = ~shifted;
            int rem = shifted;
            while (rem >= 0x20)
            {
                str.Append((char)((0x20 | (rem & 0x1f)) + 63));
                rem >>= 5;
            }
            str.Append((char)(rem + 63));
        });
    
        int lastLat = 0;
        int lastLng = 0;
        foreach (var point in points)
        {
            int lat = (int)Math.Round(point.Latitude * 1E5);
            int lng = (int)Math.Round(point.Longitude * 1E5);
            encodeDiff(lat - lastLat);
            encodeDiff(lng - lastLng);
            lastLat = lat;
            lastLng = lng;
        }
        return str.ToString();
    }
    

    Hope that helps someone else out.