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

标签 android google-maps-android-api-2

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

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();
}

此代码的问题在于,在 onMapReady 函数执行完毕后,我得到了 lat, lng。我认为纠正此问题的方法之一是创建一个 AsyncTask 以确保在 map 之前检索位置数据。但是,我正在尝试以不使用 AsyncTask 的方式实现它。

最佳答案

只需将创建标记的代码从 onMapReady() 移动到 onConnected(),并将 buildGoogleApiClient() 调用从onCreate()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));
    }
}

尽管如此,请注意您经常会从对 getLastLocation() 的调用中得到 null。您可以使用 requestLocationUpdates(),并在第一个位置出现时调用 removeLocationUpdates()。 看看this answer ,它有一个完整的示例,说明您正在尝试做什么。

关于android - 使用谷歌位置 API 在 android 中的 onMapReady 中获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659038/

相关文章:

android - 当使用警报管理器启动应用程序时,如何将额外内容传递给 Intent ?

java - 什么是最大线程 sleep 时间?

java - TextView Android 中的对齐问题

android - 如何将滚动条/ View 置于顶部位置?

java - Android 2.3.3 和 google map api v2 启动 Activity 时出错

Android Google Maps V2 身份验证错误

android - 更改 firebase 中 listviewitems 的 bool 值

android - 谷歌地图的夜间模式?

java - Google map APIv2 应用程序无法正常工作,不断崩溃

android - 方法: setOnMyLocationChangeListener有问题