move marker on google maps api 2

可紊 提交于 2019-11-28 05:05:45
JRowan

Make variable

 Marker now;

in this part add Marker and remove marker, of course put in the rest of your marker attributes:

 @Override
public void onLocationChanged(Location location) {

    if(now != null){
                now.remove();

            }

    TextView tvLocation = (TextView) findViewById(R.id.tv_location);

    // Getting latitude of the current location
    double latitude = location.getLatitude();

    // Getting longitude of the current location
    double longitude = location.getLongitude();

    // Creating a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);
    now = googleMap.addMarker(new MarkerOptions().position(latLng)));
    // Showing the current location in Google Map
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

}

Make the marker draggable using,

  MarkerOptions markerOptions = new MarkerOptions().position(myLaLn).title(
            "Current Location").draggable(true);
    map.addMarker(markerOptions);

& Get the dragged position & details as follows,

map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {

        @Override
        public void onMarkerDragStart(Marker marker) {
        }

        @Override
        public void onMarkerDragEnd(Marker marker) {
            Log.d(TAG, "latitude : "+ marker.getPosition().latitude);
            marker.setSnippet(marker.getPosition().latitude);
            map.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));

        }

        @Override
        public void onMarkerDrag(Marker marker) {
        }

    });

Optimized way to move marker :

marker mMarker;

After adding marker to map. while change the location you just need to set position rather than remove marker and add again.

mMarker.setPosition(new LatLon(latLng));

this will reduce the code from remove and add marker to direct set position and also reduce complexity. :)

Enjoy.

You are just moving camera on location change where as you should add marker as well then it will draw marker on current location. and before adding marker clear all the previous markers by calling googlmap.clear();

addMarker returns a reference to the marker which then later can be updated

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if(mMarker == null) {
                    mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
                } else {
                    mMarker.setPosition(latLng);
                }
            }
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!