我想在应用启动时获取设备的位置。
我一直在浏览文档,试图弄清楚出了什么问题,但我似乎无法找到它。永远不会调用onLocationChanged。
viewer.olView.fit(feature.getGeometry(), {
duration: 1000
});
答案 0 :(得分:0)
尝试获得这样的许可:它适用于我的情况
if (!checkIfAlreadyhavePermission()) {
ActivityCompat.requestPermissions(this, new String[]{"ACCESS_FINE_LOCATION"}, MY_PERMISSION_LOCATION_CODE);
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_LOCATION_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Call_location_updates();
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.gps_permission), Toast.LENGTH_LONG).show();
finish();
}
break;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
还可以像这样创建LocationRequest对象:
private final int INTERVAL = 5000;
private final int FAST_INTERVAL = 1000;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FAST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
public void Call_location_updates(){
Location location = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (location != null) {
onLocationChanged(location);
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
//do what u want with location
}