我想使用Google API获取GPS位置。
我的代码:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
@Override
public void onConnected(Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
double lat = mLocation.getLatitude();
double lon = mLocation.getLongitude();
}
我在lat
和lon
变量中没有得到任何内容。
我该如何解决?
答案 0 :(得分:1)
Lift
无需始终返回最后一个对象。如果它找不到最后一个对象,它将返回null并且您将无法获得位置。在这种情况下,建议使用以下方式请求定位:
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
您还需要实现一些接口和覆盖方法,以便通过Google API获取位置。
按照以下步骤获取位置:
首先,把它放在gradle文件中
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
然后实现必要的接口
compile 'com.google.android.gms:play-services:8.4.0'
声明实例
public class MainActivity extends BaseActivitiy implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener
将其放在private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager locationManager;
private LocationRequest mLocationRequest;
onCreate()
最后,重写必要的方法
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);