【发布时间】:2011-02-27 18:14:59
【问题描述】:
我有一些 C# 代码可以解码使用 Google 的折线算法编码的地图路径,并尝试将其转换为 VB.NET。
下面是完全运行的 C# 代码:
Collection<Double> decodePolyline(string polyline)
{
if (polyline == null || polyline == "") return null;
char[] polylinechars = polyline.ToCharArray();
int index = 0;
Collection<Double> points = new Collection<Double>();
int currentLat = 0;
int currentLng = 0;
int next5bits;
int sum;
int shifter;
while (index < polylinechars.Length)
{
// calculate next latitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polylinechars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polylinechars.Length);
if (index >= polylinechars.Length)
break;
currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
//calculate next longitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polylinechars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polylinechars.Length);
if (index >= polylinechars.Length && next5bits >= 32)
break;
currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
points.Add(Convert.ToDouble(currentLat) / 100000.0);
points.Add(Convert.ToDouble(currentLng) / 100000.0);
}
return points;
}
这是 VB.NET 代码 - 适用于经度,但不适用于纬度。
Public Function decodePolyline(ByVal polyline As String) As Collection(Of Double)
If polyline Is Nothing OrElse polyline = "" Then Return Nothing
Dim polylinechars As Char() = polyline.ToCharArray()
Dim points As New Collection(Of Double)
Dim currentLat As Integer = 0
Dim currentLng As Integer = 0
Dim next5bits As Integer
Dim sum As Integer
Dim shifter As Integer
For index As Integer = 0 To polylinechars.Length - 1
'calculate next latitude
sum = 0
shifter = 0
Do
index += 1
next5bits = AscW(polylinechars(index)) - 63
sum = sum Or (next5bits And 31) << shifter
shifter += 5
Loop While next5bits >= 32 AndAlso index < polylinechars.Length
If index >= polylinechars.Length Then
Exit For
End If
currentLat += If((sum And 1) = 1, Not (sum >> 1), (sum >> 1))
'calculate next longitude
sum = 0
shifter = 0
Do
index += 1
next5bits = AscW(polylinechars(index)) - 63
sum = sum Or (next5bits And 31) << shifter
shifter += 5
Loop While next5bits >= 32 AndAlso index < polylinechars.Length
If index >= polylinechars.Length AndAlso next5bits >= 32 Then
Exit For
End If
currentLng += If((sum And 1) = 1, Not (sum >> 1), (sum >> 1))
points.Add(Convert.ToDouble(currentLat) / 100000.0)
points.Add(Convert.ToDouble(currentLng) / 100000.0)
Next
Return points
End Function
缺少什么?
编辑:解决了这个问题(我在下面的答案中更正了代码,我无法再选择 2 天作为答案)。
【问题讨论】:
-
(删除了我的答案,因为我认为它没有帮助,而且我的 VB 已退化为只读,所以我无法仅凭一眼修复)
-
在什么情况下不起作用?它编译吗?显示错误的结果,与 C# 版本不同?
-
给出不正确的纬度输出。
-
也许只有我一个人,但我认为在 for 循环中更改循环索引的值是一件坏事。
-
是的-将其改回
while(尽管for确实有效)-问题在于增加循环索引-C#中的index++返回原始值,而转换后的代码给出了递增的值(下面我的答案中的更正代码)。