Reputation: 14897
I have an Android app with a GoogleMap and I want to draw a Polyline on it. For that I'm using PolyUtils.decode()
. But if it is called with my encoded String, I get an IndexOutOfBoundsException
.
This is my piece of code:
private void drawPolyLine() {
List<Trail> trails = mVehicle.getTrails();
for (Trail trail : trails) {
String encodedPolyline = trail.getTrail();
String color = trail.getColor();
List<LatLng> locations = PolyUtil.decode(encodedPolyline);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(locations.toArray(new LatLng[locations.size()]))
.width(5)
.color(parseColor(color)));
}
}
The encoded String that is passed to PolyUtil.decode()
is:
"0ee24344-9647-4592-92e7-a51b71008f4b"
And the stack trace looks like this:
java.lang.StringIndexOutOfBoundsException: length=36; index=36
E/AndroidRuntime: at java.lang.String.indexAndLength(String.java:500)
E/AndroidRuntime: at java.lang.String.charAt(String.java:494)
E/AndroidRuntime: at com.google.maps.android.PolyUtil.decode(PolyUtil.java:313)
E/AndroidRuntime: at net.my.domain.views.fragments.VehicleMapFragment.drawPolyLine(VehicleMapFragment.java:140)
...
What might possibly cause an IndexOutOfBoundsException
like this? Is it my String that is invalid? How can I check whether or not an encoded Polyline String is valid? Can someone post me a valid example of a valid encoded Polyline?
Upvotes: 1
Views: 1229
Reputation: 377
Some encoded "overview_polyline" that we get from that directions response is encoded, has double encoded backslashes. To work in the request for a static map, the double \ needs to be translated to \
Try to converse here: https://developers.google.com/maps/documentation/utilities/polylineutility
Upvotes: 1
Reputation: 18262
The encoded String
that you are passing to PolyUtil.decode()
does not seem to be a valid encoded polyline. It seems to be a UUID.
The IndexOutOfBoundsException
is caused the by an invalid encoded polyline.
Here is an example of encoding/decoding a polyline:
// Encoding
List<LatLng> locations2Encode = new ArrayList<LatLng>();
locations2Encode.add(new LatLng(40.1d, -3.1d));
locations2Encode.add(new LatLng(40.2d, -3.2d));
locations2Encode.add(new LatLng(40.3d, -3.3d));
locations2Encode.add(new LatLng(40.4d, -3.4d));
String encodedPolyline = PolyUtil.encode(locations2Encode);
// Decoding
List<LatLng> locations = PolyUtil.decode(encodedPolyline);
In this case the String representing the encoded polyline is
_`wsF~m|Q_pR~oR_pR~oR_pR~oR
According to the documentation it seems that there is no way to check if a encoded polyline is valid rather that decoding it.
You can find more examples and more info about encoding and decoding polylines in the documentation.
Upvotes: 2