Encode the polyline of latitude and longitude to a

2019-07-27 11:13发布

问题:

anyone can have code to encode the polyline(array of ) latitude and longitude value to the ascii string in java

for e.g.

my array was in java

latlng{
  {22296401,70797251},
  {22296401,70797451},
  {22296401,70797851}
}

this above value store into the List object as GeoPoint type like

List<GeoPoint> polyline

and want to convert into ascii string like this

a~l~Fjk~uOwHJy@P

I need method which accept array of latlng value and return the ascii string any help will be appreciate thanks in advance

回答1:

I got the answer from this post

this two function was needed to encode the polyline array into the ascii string

private static String encodeSignedNumber(int num) {
    int sgn_num = num << 1;
    if (num < 0) {
        sgn_num = ~(sgn_num);
    }
    return(encodeNumber(sgn_num));
}

private static String encodeNumber(int num) {

    StringBuffer encodeString = new StringBuffer();

    while (num >= 0x20) {
        encodeString.append((char)((0x20 | (num & 0x1f)) + 63));
        num >>= 5;
    }

    encodeString.append((char)(num + 63));

    return encodeString.toString();

} 

for testing try the co-ordinate from this site and compare the output

here is the snippet

StringBuffer encodeString = new StringBuffer();

String encode = Geo_Class.encodeSignedNumber(3850000)+""+Geo_Class.encodeSignedNumber(-12020000);                       
encodeString.append(encode);
encode = Geo_Class.encodeSignedNumber(220000)+""+Geo_Class.encodeSignedNumber(-75000);                      
encodeString.append(encode);
encode = Geo_Class.encodeSignedNumber(255200)+""+Geo_Class.encodeSignedNumber(-550300);                     
encodeString.append(encode);

Log.v("encode string", encodeString.toString());

from the co-ordinate link you getting this point

Points: (38.5, -120.2), (40.7, -120.95), (43.252, -126.453)

ok so now you think the co-ordinate are why different see when you get new co-ordinate then you have subtract from the previous one for example

1. 3850000,-12020000 => 3850000,-12020000
2. 4070000,-12095000 => (4070000 - 3850000),(-12095000 - -12020000) => +220000, -75000

that value you have to pass to the encodeSignedNumber() method and you get the ascii value for that co-ordinate

and so on....