对于其他遇到相同情况的人,我发现了一个名为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()
请注意,上面是一个非常普遍的例子,遵循OP的代码。
最终,这可能会使其他人不必自己编写WKT解析器。
特定于Nutiteq的代码:
在我的情况下,我需要将多行字符串作为矢量图层绘制在Nutiteq地图上。我意识到OP是在询问Google Map Android API,但是如果任何读者也在使用Nutiteq(或者如果该算法适用于其他地图API),则这是Nutiteq特定的代码:
geomLayer.clear();
Projection projection = geomLayer.getProjection();
for(int lineIndex = 0; lineIndex < geometry.getNumGeometries(); lineIndex++){
Geometry lineGeometry = geometry.getGeometryN(lineIndex);
ArrayList<MapPos> linePositions = new ArrayList<MapPos>(lineGeometry.getCoordinates().length);
for(Coordinate coordinate : lineGeometry.getCoordinates()){
MapPos linePosition = new MapPos(projection.fromWgs84(coordinate.x, coordinate.y));
linePositions.add(linePosition);
}
Line line = new Line(linePositions, new DefaultLabel("some label"), lineStyle), null);
geomLayer.add(line);
}
请注意,
lineStyleSet
和
geomLayer
是在活动的
onCreate
中创建的,并且可以在
这里进行研究。
geomLayer
很简单;这是我的
lineStyleSet
:
关于
lineStyle
的说明,它先前已经被创建并保存为实例变量,就像这样:
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);