对于其他有同样情况的人,我发现了一个名为JTS Topology Suite的开源库,它能够解析 Java 中的 WKT 字符串。我的应用程序中的一个基本示例如下所示:
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(routeResponse.get(yourWKTMultilineString);
然后,您可以像这样遍历各个行:
for(int lineIndex = 0; lineIndex < geometry.getNumGeometries(); lineIndex++){
Geometry lineGeometry = geometry.getGeometryN(lineIndex);
//... other stuff
}
如有必要,您可以像这样获取每条线的各个坐标:
Coordinate[] lineCoordinates = lineGeometry.getCoordinates();
Note that the above is a very general example which follows the OP's code.
Ultimately, this might save others from having to roll their own WKT parser.
Nutiteq-Specific Code:
In my case, I needed to draw a multiline string as a vector layer on a Nutiteq map. I realize the OP was asking about the google map android API, however in case any reader is also using Nutiteq (or if this algorithm is relevant for other map APIs), this is the nutiteq specific code:
geomLayer.clear(); // clear the old vector data
Projection projection = geomLayer.getProjection(); // Map's projection type
// Iterate through the individual lines of our multi-line geometry
for(int lineIndex = 0; lineIndex < geometry.getNumGeometries(); lineIndex++){
Geometry lineGeometry = geometry.getGeometryN(lineIndex);
ArrayList<MapPos> linePositions = new ArrayList<MapPos>(lineGeometry.getCoordinates().length);
// Iterate through this line's coordinates
for(Coordinate coordinate : lineGeometry.getCoordinates()){
// My server returns coordinates in WGS84/EPSG:4326 projection while the map
// uses EPSG3857, so it is necessary to convert before adding to the
// array list.
MapPos linePosition = new MapPos(projection.fromWgs84(coordinate.x, coordinate.y));
linePositions.add(linePosition);
}
// Finally, add the line data to the vector layer
Line line = new Line(linePositions, new DefaultLabel("some label"), lineStyle), null);
geomLayer.add(line);
}
Note that the lineStyleSet
and geomLayer
are created previously in the activity's onCreate
and can be researched here. The geomLayer
is simple; here is my lineStyleSet
:
Note about lineStyle, it was created previously and is saved as an instance variable, like so:
Bitmap lineMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.line);
this.lineStyleSet = new StyleSet<LineStyle>();
LineStyle lineStyle = LineStyle.builder().setLineJoinMode(LineStyle.NO_LINEJOIN).setWidth(0.2f).setColor(Color.RED).setBitmap(lineMarker).build();
lineStyleSet.setZoomStyle(minZoom, lineStyle);