Google map Polygon with draggable marker

Hi,

I trying onMapClick to generate a marker in the map. When I click the button it would generate the polygon within those markers.

I have the following question regarding this task.

Question 1:- When I put random marker I got the cross line in that markers like below
1

here is my expected output.
2

Question 2:- I would add drag functionality on the marker and but When I drag the marker I would like to move polygon as well but I don’t know how to achieve this task.

I got the marker moving but I don’t know how to move lines with the marker.
Here is my output.
3
4

Here is my java code

public class MapsActivity extends AbstractMapActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    int MarkerNumber = 1;
    List<LatLng> points;
    List<Marker> Markers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (readyToGo()) {
            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);
            points = new ArrayList<LatLng>();
            Markers = new ArrayList<Marker>();
            if (savedInstanceState == null) {
                mapFragment.getMapAsync(this);
            }

            mapFragment.getMapAsync(this);
        }
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        CameraUpdate center =
                CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                        -73.98180484771729));
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
        mMap.moveCamera(center);
        mMap.animateCamera(zoom);
        mMap.setIndoorEnabled(false);

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng point) {

                MarkerOptions marker = new MarkerOptions().position(new LatLng(point.latitude, point.longitude)).title("" + (MarkerNumber)).draggable(true);
                MarkerNumber = MarkerNumber++;
                mMap.addMarker(marker).showInfoWindow();
                System.out.println(point.latitude + "---" + point.longitude);
                points.add(new LatLng(point.latitude, point.longitude));
//                System.out.println(Arrays.toString(points.toArray()));
            }
        });
    }

    public void closePolygon(View view) {

        PolygonOptions rectOptions = new PolygonOptions().clickable(true);

        rectOptions.addAll(points);
        // Get back the mutable Polygon
        Polygon polygon = mMap.addPolygon(rectOptions);
        points.clear();
        Markers.clear();
    }

    public void newPolygon(View view) {

        mMap.clear();
    }
}

XML code

<?xml version="1.0" encoding="utf-8"?>
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_marginStart="3dp"
    android:layout_marginTop="-1dp"
    android:layout_marginEnd="-2dp"
    tools:context=".MapsActivity">


</fragment>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="26dp"
    android:layout_marginBottom="32dp"
    android:orientation="vertical"
    android:weightSum="2">

    <Button
        android:id="@+id/bt_close_polygon"
        android:layout_width="140dp"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:background="@color/teal"
        android:padding="8dp"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:onClick="closePolygon"
        android:layout_marginBottom="8dp"
        android:text="@string/close_polygon" />

    <Button
        android:id="@+id/bt_new_polygon"
        android:layout_width="140dp"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:background="#ED1C21"
        android:padding="8dp"
        android:onClick="newPolygon"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:text="@string/new_polygon" />
</LinearLayout>

Looking forward to your response.
Thank You

1 Like

You may need to reorder the vertices of your polygon. For example, if the southeast one was added last, and the northwest one was the next-to-last, I can see Google Maps drawing your edges that way.

To be honest, neither do I. I have not used the Google Maps API in nearly two years, and I have never attempted to render a polygon as part of moving a marker.

I apologize for not being of greater use on this subject!

1 Like

You may need to reorder the vertices of your polygon. For example, if the southeast one was added last, and the northwest one was the next-to-last, I can see Google Maps drawing your edges that way.

Could you able to refer some links or code that I can check?

I do not have any links or code to offer you for a draggable polygon, sorry.

I mean I need help in recording the vertices.Do you have any links or code for the suggestions?

I have not done an on-the-fly polygon. I have only ever created polygons either from static metadata or from server-supplied vertices. In both cases, they were ordered properly.

While my work in discrete mathematics was ~30 years ago, I seem to recall that there are algorithms that will order the vertices the way that you need, so the sequential list forms the perimeter. But I do not have any specific code or links to offer you, sorry.

Could you able to help me with Drag listener because I would like to upadate dragged marker in list.

Do you know how to update that?

My chapter on MapsV2 in The Busy Coder’s Guide to Android Development has a section on dragging markers.

I am uncertain how you want to to “update dragged marker in list”, though.

For example, I have put markers using the touch event and drawing polygon using the list of LatLog after pressing the button. Then I would like to move one of the markers using drag event so I wanna update that dragged marker in the latlog list.

Here is my code

    public class MapsActivity extends AbstractMapActivity implements OnMapReadyCallback, GoogleMap.OnMarkerDragListener {

    private GoogleMap mMap;
    List<LatLng> points;
    List<MarkerOptions> Markers;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (readyToGo()) {
            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);
            points = new ArrayList<LatLng>();
            Markers = new ArrayList<MarkerOptions>();
            if (savedInstanceState == null) {
                mapFragment.getMapAsync(this);
            }

            mapFragment.getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        CameraUpdate center =
                CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                        -73.98180484771729));
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
        mMap.moveCamera(center);
        mMap.animateCamera(zoom);
        mMap.setIndoorEnabled(false);

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng point) {

                MarkerOptions marker = new MarkerOptions().position(new LatLng(point.latitude, point.longitude)).draggable(true);
                mMap.addMarker(marker).showInfoWindow();
                System.out.println(point.latitude + "---" + point.longitude);
                points.add(new LatLng(point.latitude, point.longitude));
                Markers.add(marker);
//                System.out.println(Arrays.toString(points.toArray()));
            }
        });


    }


    public void closePolygon(View view) {

        PolygonOptions rectOptions = new PolygonOptions().clickable(true);

        rectOptions.addAll(points);
        // Get back the mutable Polygon
        Polygon polygon = mMap.addPolygon(rectOptions);
//        polygon.remove();
        points.clear();
        Markers.clear();
    }

    public void newPolygon(View view) {

        mMap.clear();
    }

    @Override
    public void onMarkerDragStart(Marker marker) {
        
    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

    }

}

update the points list in the drag listener.

But what does “update” mean? The Marker is being updated by Maps V2, in terms of its position.

If by “the latlog list” you mean the points list, that list cannot be updated, as you do not know what to replace. If you put a tag on the Marker via setTag() after you create it (via mMap.addMarker()), you could get that back in your onMarkerDragEnd() method via getTag(). If you replace points with a Map<String, LatLng>, where the map key is the tag, you could then replace the LatLng for the tag of the dragged Marker.

1 Like

how to make multiple polygon on Google Map I am using
private List<LatLng> points = new ArrayList<>();
but its create only one polygon when we draw another then last polygon deleted so anyone please help me thanks in advance