1

I want to draw a freehand polygon on a map on android studio, and I don't know what to do I have the map already ublic class MapsActivity extends FragmentActivity implements 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));
}}
Shashanth
  • 4,995
  • 7
  • 41
  • 51
ras
  • 5
  • 2

1 Answers1

0

If by hand free you mean a polygon created by the user touching the map, I should recommend you intercept touch or click events on the map object and get the LatLng of the exact clicked location. Then add that point to a list of points for your polygon. You can decide whatever : redraw the polygon every time there is a new click or something else that comes in your mind.

In the following example I intercept clicks and redraw the polygon with current stored points for every new click. I can decide to have as many polygons as I want but I want just one now.

@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

            }
        });
}}
Gratien Asimbahwe
  • 1,606
  • 4
  • 19
  • 30