Coordinate - Latitude and Longitude Android

Asked

Viewed 2,285 times

1

I need when recording a client on Android, pick up the location where the phone was when it was recorded.

My question is:

  • How to get latitude and longitude on Android (ex: getLatitude())?
  • How to view it on Google Maps (via Android)?

Thank you

PS: from preference to examples that work in Android Studio.

1 answer

2

Here is an example of implementation ( Source )

First you should add the following permission into your AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION”/>

Mapsactivity.java:

import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;



public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    /**
     * Mapa da aplicação
     */
    private GoogleMap mMap;

    /**
     * Responsável por disponibilizar a localização do smartphone.smartphone
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Guarda a ultima posição do smartphone.
     */
    private Location mLastLocation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Vamos instanciar o GoogleApiClient, caso seja nulo
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this) // Interface ConnectionCallbacks
                    .addOnConnectionFailedListener(this) //Interface OnConnectionFailedListener
                    .addApi(LocationServices.API) // Vamos a API do LocationServices
                    .build();
        }
    }
    /*
     * Ao iniciar, connectamos !
     */
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    /*
      * Ao finalizar, desconectamos!
     */
    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    }



    /*
     * Método invocado quando o GoogleApiClient conseguir se conectar
     */
    @Override
    public void onConnected(Bundle bundle) {
        // pegamos a ultima localização
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            if(mMap != null){
                // Criamos o LatLng através do Location
                final LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                // Adicionamos um Marker com a posição...
                mMap.addMarker(new MarkerOptions().position(latLng).title("Minha Posição"));
                // Um zoom no mapa para a seua posição atual...
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

            }

        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    /*
     * Neste método você deverá tratar caso não consiga se conncetar...
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.