views:

139

answers:

2

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);
+2  A: 

csharp-polyline-encoder

Mitch Wheat
I found that too. It's much more complex than what I'm asking for. It doesn't implement anything close to the signature in the OP.
Drew Noakes
+3  A: 

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.

Drew Noakes