Java how to move a marker on google maps in android studio

Java how to move a marker on google maps in android studio

To move a marker on Google Maps in Android Studio, you can use the setPosition method of the Marker class.

Here is an example of how you can move a marker on Google Maps in Android Studio:

refer‮al:ot ‬utturi.com
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private Marker marker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 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);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        
        // Add a marker to the map and store a reference to it
        LatLng currentLocation = new LatLng(37.4219983, -122.084);
        marker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
    }
    
    public void moveMarker(View view) {
        // Move the marker to a new location
        LatLng newLocation = new LatLng(37.7749, -122.4194);
        marker.setPosition(newLocation);
    }
}

In this example, the MainActivity class implements the OnMapReadyCallback interface and overrides the onMapReady method to set up a Google Map with a marker. The moveMarker method is called when a button is clicked, and it uses the setPosition method to move the marker to a new location.

Keep in mind that you need to add the necessary dependencies and configure the Google Maps API key in your project to use the Google Maps API in Android Studio. You can refer to the Google Maps API documentation for more information on how to set up and use the Google Maps API in Android Studio.

Created Time:2017-11-03 23:27:11  Author:lautturi