Waqas Yousaf
Waqas Yousaf

Reputation: 11

longclick on map to open alert dialog to create a marker in the Google map

I am new in android. I want this functionality, In google map activity, when i long click on Map, it shows a alert dialog to create a marker on the map, alert dialog has two buttons, one is for create marker and other is for cancel. plz anyone help me. how to create a marker by using alert dialog.

Upvotes: 1

Views: 1524

Answers (2)

Simas
Simas

Reputation: 44118

It's pretty easy, really. Listen to long clicks with onMapLongClickListener and show dialog, if positive button is pressed create a marker. Here's an example:

public class MainActivity extends FragmentActivity implements 
        DialogInterface.OnClickListener {

    private GoogleMap mMap;
    private LatLng mClickPos;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Init activity and map

        mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                mClickPos = latLng;
                new AlertDialog.Builder(MainActivity.this)
                        .setPositiveButton("Create", MainActivity.this)
                        .setNegativeButton("Cancel", null)
                        .show();
            }
        });
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        mMap.addMarker(new MarkerOptions().position(mClickPos));
    }

}

Upvotes: 2

CodeMonkey
CodeMonkey

Reputation: 1426

You can handle both click and long-click events on the Map as shown in the documentation.

Map click/long click events

If you want to respond to a user tapping on a point on the map, you can use an OnMapClickListener which you can set on the map by calling GoogleMap.setOnMapClickListener(OnMapClickListener). When a user clicks (taps) somewhere on the map, you will receive an onMapClick(LatLng) event that indicates the location on the map that the user clicked. Note that if you need the corresponding location on the screen (in pixels), you can obtain a Projection from the map which allows you to convert between latitude/longitude coordinates and screen pixel coordinates.

You can also listen for long click events with an OnMapLongClickListener which you can set on the map by calling GoogleMap.setOnMapLongClickListener(OnMapLongClickListener). This listener behaves similarly to the click listener and will be notified on long click events with an onMapLongClick(LatLng) callback.

Override the onMapClick(LatLng) and create your marker using the LatLng that you have received.

Upvotes: 1

Related Questions