Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Google Map v2 - move marker to clicked position and update geo coordinates

In my app I detect user's current location automatically and center the map around the marker.

I want to enable the user to click elsewhere on the map, and the marker to appear at the position they clicked, and the lat/lon to be updated to that new position.

How do I do that

like image 849
Kaloyan Roussev Avatar asked Jan 31 '26 08:01

Kaloyan Roussev


2 Answers

try this

 Marker marker;
 GoogleMap mMap;

 mMap.setOnMapClickListener(new OnMapClickListener() {

        @Override
        public void onMapClick(LatLng latlng) {
            // TODO Auto-generated method stub

            if (marker != null) {
                marker.remove();
            }
            marker = mMap.addMarker(new MarkerOptions()
                    .position(latlng)
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            System.out.println(latlng);

       }
   });
like image 118
Rakesh Rangani Avatar answered Feb 01 '26 20:02

Rakesh Rangani


In order to add a marker with the current location you have to implement LocationListener

With the following code you can add a marker with your location and move the camera:

            public void onLocationChanged(Location location) {

            map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude()))
                    .title("My Location"));

            /* ..and Animate camera to center on that location !
             * (the reason for we created this custom Location Source !) */
            map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
        }

In order to add a maker when the user taps inside the map you can use OnMapLongClickListener

    @Override
    public void onMapLongClick(LatLng point) {

        mMap.addMarker(new MarkerOptions()
            .position(point)
            .snippet(""));
    }
like image 37
Ariel Carbonaro Avatar answered Feb 01 '26 22:02

Ariel Carbonaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!