How to get Latitude and Longitude from Google Map Marker in Android

Working with Google Map is one of the feature requirements for many kind of android applications.

Google Map is usually use in android apps where users need to locate certain point in a map or to create a visual representation of distance between two different points in a map.

In my previous android Google Map code example, we explored how to get LatLng from address using Geocoding API.

Imagine we have a map with a marker in a particular position and we want to get the latitude and longitude of this marker position in android how do you think we can achieve this task?

Just like in many programming problems, there might be multiple ways to solve them.

We will look at few solutions that will solve our task.

Create a new Android Project

  • Open Android Studio
  • Go to file menu
  • Select  new
  • Enter project name
  • Enter activity name
  • Select Google Map Activity
  • Click on finish button to create a new android project

Add Google API Key

In the resource folder res > values, open the google_map_api.xml file and add your project Google Map API key.

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:5A:31:B4:7F:F9:46%3Bcom.inducesmile.googlemapexamples

    You can also add your credentials to an existing key, using these values:

    Package name:
    57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:5A:31:B4:7F:F9:46

    SHA-1 certificate fingerprint:
    57:A8:DD:42:FF:9E:88:E6:EC:69:71:B7:0D:2C:5A:31:B4:7F:F9:46

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_API_KEY</string>
</resources>

First Solution

The first solution we will explore is using onMapLongClick(LatLng latLng) to get the longitude and latitude of a location in a map.

We will add the onMapLongClick event listener interface and in the callback method the LatLng instance is passed as a parameter.

With the LatLng instance we can get the latitude and longitude values of the selected location on the map.

The MapActivity class will appear like below code.

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.inducesmile.googlemapexamples.utils.GeoLocationUtils;

import java.util.Objects;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {

    private static final String TAG = MapsActivity.class.getSimpleName();

    private GoogleMap mMap;

    private static final String ADDRESS = "Nygatan 20 Horby, Sweden";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        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);
        Objects.requireNonNull(mapFragment).getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnMapLongClickListener(this);

        if(!TextUtils.isEmpty(ADDRESS)){
            LatLng latLng = GeoLocationUtils.getLocationFromAddress(this, ADDRESS);
            addCameraToMap(googleMap, latLng);
        }
    }

    private void addCameraToMap(GoogleMap googleMap, LatLng latLng){
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng)
                .zoom(16)
                .build();
        googleMap.addMarker(new MarkerOptions().position(latLng).title("Lagos"));
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        Log.d(TAG, "Longitude Value " + latLng.longitude + " Latitude value " + latLng.latitude);
    }

}

Second Solution

In second solution, we are going to override the onMarkerDragEnd(Marker marker).

The onMarkerDragEnd(Marker marker) has a Marker object passed as its parameter.

With the instance of the Marker object, we can call its getPosition() method to return the current latitude and longitude values of the location.

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.inducesmile.googlemapexamples.utils.GeoLocationUtils;

import java.util.Objects;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener {

    private static final String TAG = MapsActivity.class.getSimpleName();

    private GoogleMap mMap;

    private static final String ADDRESS = "Nygatan 20 Horby, Sweden";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        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);
        Objects.requireNonNull(mapFragment).getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnMapLongClickListener(this);
        mMap.setOnMarkerDragListener(this);

        if(!TextUtils.isEmpty(ADDRESS)){
            LatLng latLng = GeoLocationUtils.getLocationFromAddress(this, ADDRESS);
            addCameraToMap(googleMap, latLng);
        }
    }


    private void addCameraToMap(GoogleMap googleMap, LatLng latLng){
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng)
                .zoom(16)
                .build();
        googleMap.addMarker(new MarkerOptions().position(latLng).draggable(true).title("Lagos"));
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }


    @Override
    public void onMapLongClick(LatLng latLng) {
        Log.d(TAG, "Longitude Value " + latLng.longitude + " Latitude value " + latLng.latitude);
    }


    @Override
    public void onMarkerDragStart(Marker marker) {
        Log.d(TAG, "start");
    }

    @Override
    public void onMarkerDrag(Marker marker) {
        Log.d(TAG, "drag");
    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        LatLng position = marker.getPosition();
        Log.d(TAG, "Lng Value " + position.longitude + " Lat value " + position.latitude);
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment