Android系统。谷歌地图。如何从数组中绘制多边形

时间:2017-04-09 17:02:10

标签: android google-maps-android-api-2 wkt

我是Android应用开发的新手。 我有WKT(POLYGON) 如何从wkt在谷歌地图上绘制多边形?

我试试

    String str;

        ArrayList<String> coordinates = new ArrayList<String>();

        str = tvwkt.getText().toString();

        str = str.replaceAll("\\(", "");
        str = str.replaceAll("\\)", "");
        str = str.replaceAll("POLYGON", "");
        str = str.replaceAll("POINT", "");
        str = str.replaceAll(", ", ",");
        str = str.replaceAll(" ", ",");
        str = str.replaceAll(",,", ",");


        String[] commatokens = str.split(",");
            for (String commatoken : commatokens) {
                coordinates.add(commatoken);
        }

        for (int i = 0; i < coordinates.size(); i++) {

            String[] tokens = coordinates.get(i).split("\\s");
            for (String token : tokens) {

                listPoints.add(token);
            }

        }

        PolygonOptions rectOptions = new PolygonOptions().addAll(listPoints).strokeColor(Color.BLUE).fillColor(Color.CYAN).strokeWidth(7);

        polygon = mMap.addPolygon(rectOptions);

但它没有用。 请告诉我。 感谢。

1 个答案:

答案 0 :(得分:0)

我能做到。

从WKT读取LatLong并添加到Array

private LatLng[] GetPolygonPoints(String polygonWkt) {

    Bundle bundle = getIntent().getExtras();
    wkt = bundle.getString("wkt");
    ArrayList<LatLng> points = new ArrayList<LatLng>();
    Pattern p = Pattern.compile("(\\d*\\.\\d+)\\s(\\d*\\.\\d+)");
    Matcher m = p.matcher(wkt);
    String point;

    while (m.find()){
        point =  wkt.substring(m.start(), m.end());
        points.add(new LatLng(Double.parseDouble(m.group(1)), Double.parseDouble(m.group(2))));
    }
    return points.toArray(new LatLng[points.size()]);

}

然后绘制多边形

    public void Draw_Polygon() {

    LatLng[] points = GetPolygonPoints(polygonWkt);

        Polygon p = mMap.addPolygon(
                new PolygonOptions()
                        .add(points)
                        .strokeWidth(7)
                        .fillColor(Color.CYAN)
                        .strokeColor(Color.BLUE)
        );

    //Calculate the markers to get their position
    LatLngBounds.Builder b = new LatLngBounds.Builder();
    for (LatLng point : points) {
        b.include(point);
    }
    LatLngBounds bounds = b.build();
    //Change the padding as per needed
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 20,20,5);
    mMap.animateCamera(cu);

}

最后

public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;

    mMap.setMapType(MAP_TYPE_HYBRID);

    mMap.getUiSettings().setRotateGesturesEnabled(false);

    mMap.getUiSettings().setMapToolbarEnabled(false);

    LatLng[] points = GetPolygonPoints(polygonWkt);

    if (points.length >3){

        Draw_Polygon();

    }
    else {

        Add_Markers();

    }

}