Google encodePolyline algorithm

Here`s an implementation of the Google Encode Polyline algorithm in Xojo which is used to convert an array of coordinates into a single string.

Here`s a test suite to test your results: Interactive Polyline Encoder Utility  |  Google Maps Platform  |  Google Developers

You’re then able to create static map images with mapbox for example.

Protected Function encodePolyline(coordinates() as pair, usePrintserver as Boolean = false) as string
  Var ret As String
  
    Var oldLat, oldLng As Double = 0
    For i As Integer = 0 To coordinates.Ubound
      Var newLat, newLng As Double
      
      If oldLat = 0 And oldLng = 0 Then
        newLat = coordinates(i).Left.DoubleValue 
        newLng = coordinates(i).Right.DoubleValue 
      Else
        newLat = coordinates(i).Left.DoubleValue - oldLat
        newLng = coordinates(i).Right.DoubleValue - oldLng
      End If
      
      ret = ret + encodePolylineLeg(newLat)
      ret = ret + encodePolylineLeg(newLng)
      
      oldLat = coordinates(i).Left.DoubleValue
      oldLng = coordinates(i).Right.DoubleValue
      
    Next
    
    
  Return ret
End Function
Private Function encodePolylineLeg(value as double) as string
  Var s As String
  Var base As Integer = 256 ^ 4
  Var minus As Boolean = (value < 0)
  
  If minus Then
    value = -value
  End If
  
  Var x As Integer = value * 100000
  //Break
  
  If minus Then
    x = base - x
  End If
  
  x = x * 2
  
  If minus Then
    x = (base * 2) - 1 - x
  End If
  
  While x > 0 
    Var y As Integer
    y = x Mod 32
    x = x / 32
    
    If x > 0 Then
      y = y + 32
    End If
    
    y = y + 63
    
    //Self.charcodes = Self.charcodes + y.ToString + " "
    s = s + Encodings.ASCII.Chr(y)
    
  Wend
  
  Return s
End Function

5 Likes

Update

HereMaps uses a slightly different algorithm to encode polylines.

I created a Git repo for both implementations (HereMaps & Google):

4 Likes