使用谷歌位置API在android中的onMapReady中获取当前位置

2024-04-23

我试图在我的应用程序内的谷歌地图上显示用户的当前位置,但我不想在用户移动时不断更新位置。应记录并显示他的初始位置,直到他关闭应用程序。我为此编写了以下代码:

private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
Location mLastLocation;
double lat =0, lng=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    buildGoogleApiClient();

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


}

private void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}


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

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    LatLng loc = new LatLng(lat, lng);
    mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();
    }
}

@Override
protected void onStart() {
    super.onStart();

    mGoogleApiClient.connect();
}

这段代码的问题是我得到了lat, lng之后onMapReady函数已经执行完毕。我认为纠正这个问题的方法之一是创建一个AsyncTask以确保在地图之前检索位置数据。但是,我正在尝试以一种不使用的方式来实现这一点AsyncTask.


只需移动创建标记的代码即可onMapReady() to onConnected(),然后转移呼叫buildGoogleApiClient()来电来自onCreate() to onMapReady():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    //buildGoogleApiClient();

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

    // Add a marker in Sydney and move the camera
    mMap.setMyLocationEnabled(true);

    //add this here:
    buildGoogleApiClient();

    //LatLng loc = new LatLng(lat, lng);
    //mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = mLastLocation.getLatitude();
        lng = mLastLocation.getLongitude();

        LatLng loc = new LatLng(lat, lng);
        mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
    }
}

不过,请注意,您经常会从调用中得到 nullgetLastLocation()。您可以使用requestLocationUpdates(),并致电removeLocationUpdates()当第一个位置进入时。 看一眼这个答案 https://stackoverflow.com/a/34582595/4409409,它有一个完整的示例,说明您正在尝试做什么。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用谷歌位置API在android中的onMapReady中获取当前位置 的相关文章

随机推荐