如何使用googleapiClient获取当前位置然后放置标记

时间:2016-05-17 08:09:25

标签: android google-maps-markers google-api-client

我想通过以下代码使用GoogleApiClient获取当前位置

@Override
public void onConnected(@Nullable Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if(mLastLocation != null)
    {
        currentLat = mLastLocation.getLatitude();
        currentLon = mLastLocation.getLongitude();
    }else
    {
        Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
    }
}

然后我确实想把标记放在当前位置,我的问题是mLastlocation仍为空

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

    if(mLastLocation != null)
    {
        MarkerOptions marker = new MarkerOptions()
                .position(new LatLng(currentLat, currentLon))
                .title("My Current Location");

        dGoogleMap.addMarker(marker);
        dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(currentLat, currentLon), 16));
    }
}

或者这是我的错误,误解了异步的流程,或者只是我的糟糕逻辑需要改进。

1 个答案:

答案 0 :(得分:0)

onMapReady方法

中添加以下内容
dGoogleMap.setMyLocationEnabled(true);