Skip to content Skip to sidebar Skip to footer

Get A Current Location With Maps Api On Android Studio

I ask, how to create a script, for android, to get a current location with google maps api v2 for android. Now my scrpt take the location specifying the cordinates. I post it my ja

Solution 1:

In your onCreate() method, type this:

SupportMapFragmentmapFragment= (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.mapfragment);
    mapFragment.getMapAsync(this);

Make your Activity implement LocationListener, onMapReadyCallback and GoogleApiClient.ConnectionCallbacks interfaces. In the methods of that interfaces:

onMapReady (from onMapReadyCallbacks):

    publicvoidonMapReady(GoogleMap map) {
        //mapa is your GoogleMap variable
        mapa=map;

    }

Doing this, you make sure your map is ready for working.

In onConnected method (from GoogleApiClient.ConnectionCallbacks interface) you get your location:

@OverridepublicvoidonConnected(Bundle bundle) {

    Location lkn=LocationServices.FusedLocationApi.getLastLocation(
            gApiClient);
    if(myLocation==null){
        myLocation=newLocation("");
    }
    if(lkn!=null){

        myLocation.setLatitude(lkn.getLatitude());
        myLocation.setLongitude(lkn.getLongitude());
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            gApiClient, mLocationRequest, this);
}

And finally, in onLocationChanged (from LocationListener interface):

@OverridepublicvoidonLocationChanged(Location location) {
    //myLocation is a class variable, type Location
    myLocation.setLatitude(location.getLatitude());
    myLocation.setLongitude(location.getLongitude());

}

So, every time the phone have a new location you will receive it in that method.

You will need to implement this two methods too:

//call this method in your onCreate()protected synchronized voidbuildGoogleApiClient() {
    //gApiClient is a class variable, type GoogleApiClient
    gApiClient = newGoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(newGoogleApiClient.OnConnectionFailedListener() {
                @OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {
                    Log.i("Map", "Conection failed");
                }
            })
            .addApi(LocationServices.API)
            .build();
    gApiClient.connect();
    createLocationRequest();
}

protectedvoidcreateLocationRequest() {
    mLocationRequest = newLocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

Post a Comment for "Get A Current Location With Maps Api On Android Studio"