C# implementation of Google’s ‘Encoded Polyline Algorithm’

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)