Search code examples
androidgoogle-mapslinepolygon

extra line in google map polygon


In the following screenshot i'm drawing a polygon by clicking the google maps. Using the setOnMapClickListener the lat lng of the clicked points (1-10 shown in image) is stored to a array list then using the method polygon as shown the polygon is drawn.

The points are clicked in the sequence as shown in the image, but I'm getting an extra line between 8 and 10. how can i get the polygon for the exact points clicked on map.

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                    polygon_list.add(latLng);
                    mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.mipmap.dot)).anchor(0.5f, 0.5f));
                }
            }
        });

public void polygon() {
        PolygonOptions opts = new PolygonOptions();
        for (LatLng location : polygon_list) {
            opts.add(location);
            poly_shape = mMap.addPolygon(opts.strokeColor(Color.RED).fillColor(Color.BLUE));
        }
    }

Map Screenshot]


Solution

  • There are a couple of suggestions that you can try.

    1. Clear polygon_list before adding the click listener.
    2. Create poly_shape once, outside the for loop.

    At the moment you add a point to PolygonOptions and create a new polygon each time inside the for loop. This may be the reason for the extra line between 8 and 10.

    The updated code will look like

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                        polygon_list.add(latLng);
                        mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.mipmap.dot)).anchor(0.5f, 0.5f));
                    }
                }
            });
    
    public void polygon() {
            PolygonOptions opts = new PolygonOptions();
            for (LatLng location : polygon_list) {
                opts.add(location);
            }
           poly_shape = mMap.addPolygon(opts.strokeColor(Color.RED).fillColor(Color.BLUE));
        }