如何在Android的Google地图中绘制自由手多边形?

时间:2019-11-22 22:28:11

标签: android google-maps polygon draw

我想在android studio的地图上绘制手绘多边形,但我不知道该怎么做 我已经有地图 公共类MapsActivity扩展FragmentActivity实现OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}}

1 个答案:

答案 0 :(得分:0)

如果“放手”是指用户通过触摸地图创建的多边形,则我建议您在地图对象上拦截触摸或单击事件,并获得确切点击位置​​的LatLng。然后将该点添加到多边形的点列表中。您可以决定:在每次有新的点击或其他想法时重新绘制多边形。

在以下示例中,我拦截了点击,并为每次新点击重新绘制了具有当前存储点的多边形。我可以决定有任意多个多边形,但现在只想要一个。

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    /*polygon should be declared as member of the fragment class if you want just one polygon at a time*/
final List<LatLng> latLngs = new ArrayList<>(); // list of polygons
        final GoogleMap X = this.mMap; // the map

        this.googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                latLngs.add(latLng);//add the point to the list
                if (polygon != null ) polygon.remove(); // remove the previously drawn polygon 
                polygon = X.addPolygon(new PolygonOptions().addAll(latLngs).fillColor(Color.BLUE).strokeColor(Color.RED));//add new polygon

            }
        });
}}