简体   繁体   中英

Android Google map. wait for location initialization before moving Maps camera

I have this following code on my application (the aim is to have a GoogleMaps fragment) :

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
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.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
import java.util.List;

public class MapsActivity extends Activity implements LocationListener {

private GoogleMap mMap;        

private static final LatLng position_gps = new LatLng([defined,position]);
int MY_PERMISSIONS_REQUEST_FINE_LOCATION;

private static final LatLng position_gps_track1 = new LatLng([something], [something]);

/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    LocationManager locationManager;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_FINE_LOCATION);
        return;
    }
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    Location location = locationManager.getLastKnownLocation(provider);
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    if (mMap != null) {
        mMap.addMarker(new MarkerOptions().position(position_gps_track1).title("T1 - Thomas"));

        LatLng pos_gps;
        if (location == null) {    
            pos_gps = position_gps;     
        } else {                    
            pos_gps = new LatLng(location.getLatitude(), location.getLongitude());
        }
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos_gps, 15));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
        mMap.setMyLocationEnabled(true);                       
        mMap.getUiSettings().setCompassEnabled(true);          
        mMap.getUiSettings().setZoomControlsEnabled(true);    
    } else {
        Toast.makeText(this, "Services GoogleMap indisponibles!", Toast.LENGTH_SHORT).show();
    }

    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).addApi(LocationServices.API).build();


}

@Override
public void onLocationChanged(Location location) {

    int latitude = (int) (location.getLatitude());
    int longitude = (int) (location.getLongitude());
    LatLng position_gps = new LatLng(location.getLatitude(), location.getLongitude());
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position_gps, 15));
}


public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("Maps Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();
    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
    super.onStop();
    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}
}

I'd like to make the map focus on current location when the activity starts but, on the method onCreate(), the location variable is always null, and the maps focus on my defined location.

Please, how to make sure that, when the location is finally initialised, the map will zoom on my current location ?

Thx.

you need to use:

in your onCreate()

// 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);

Now overwrite the onMapReady() function and use the below code:

    @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMyLocationEnabled(true);
    mMap.addMarker(new MarkerOptions().position(position_gps_track1).title("T1 - Thomas"));

    LatLng pos_gps;
    if (location == null) {
        pos_gps = position_gps;
    } else {
        pos_gps = new LatLng(location.getLatitude(), location.getLongitude());
    }
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos_gps, 15));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
    mMap.getUiSettings().setCompassEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    }

in XML you should have:

     <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

Your class must implement the OnMapReadyCallback

public class MapsActivity extends Activity implements LocationListener ,OnMapReadyCallback { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM