Search code examples
androidgoogle-maps-android-api-2

Get lat-lng from google map intent


I am new comer in android world. Trying to get current co-ordinates from google map. I have done a sample app which opens google map as intent (from android website). What i want to do is get the lat-lng from that intent. I have done so far-

   public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @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);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
       // mMap = googleMap;
        Uri uri = Uri.parse("geo:latitude,longitude?z=17");
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
}

UPDATE: I know I can get current co-ordinate in android. But I would like to get co-ordinate from google map intent (currenlty showing marker position)?


Solution

  • Please see the GoogleMap class documentation:

    public final Location getMyLocation ()
    ...

    Returns the currently displayed user location, or null if there is no location data available.

    Returns

    • The currently displayed user location.

    Throws

    • IllegalStateException if the my-location layer is not enabled.

    Then again it also says:

    This method is deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead.

    So you can use getMyLocation() if you really want but it's not recommended. And it might return null. Or throw an exception.

    The code would then be something like:

        @Override
        public void onMapReady(GoogleMap googleMap) {
            // mMap = googleMap;
            Location myLocation;             
    
            try {
                myLocation = googleMap.getMyLocation();
            }
            catch (IllegalStateException e) {
                // Handle the exception.
            }
    
            if (!myLocation == null) {
                // Do something with the location if it's not null...
            }
            else {
                // Handle the null location.
            }
    
            Uri uri = Uri.parse("geo:latitude,longitude?z=17");
            Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }