我正在尝试在Android应用中使用自定义用户位置标记实现谷歌地图
我正在使用FusedLocationApi
来接收位置更新,并遇到一个问题,即在onLocationChanged()中,即使设备没有移动,我每次都会收到非常不同的位置,但是会停留在一个位置。
因此,用户位置和精度半径每分钟改变几次(显示正确和错误的位置)。
我知道这是因为从不同来源接收位置,但如何确定权利,忽略错误和模糊的位置?
试图实现一个函数来忽略错误的位置变化,但它不能按预期工作
在图片中,它在一分钟内看起来像用户(用户停留在一个位置):
代码
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// build GoogleApiClient
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
// create location request
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
// ... here is how I request the updates
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
/**
* Callback that fires when the location changes.
*/
@Override
public void onLocationChanged(Location location) {
// TODO herre I try to figure out which location is right and which is wrong
if (shouldIgnoreLocationChange(mLastDrawnLocation, location)) {
return;
}
// here i should proceed only with eight location...
}
/**
* Checks whether location change (coordinates) should be ignored or not
*
* @param oldLocation previous {@link Location}
* @param newLocation new {@link Location}
* @return true if coordinates change should be ignored because it is not significant
*/
private boolean shouldIgnoreLocationChange(Location oldLocation, Location newLocation) {
if (oldLocation == null) {
// didn't have any location before, so accept new
return false;
} else if (null == newLocation || !newLocation.hasAccuracy() || newLocation.getAccuracy() > 150) {
// new location got invalid or too vague accuracy so ignore it
return true;
}
// ignore change if change is smaller then 3 meters and
if (oldLocation.distanceTo(newLocation) < 3f && newLocation.getAccuracy() >= oldLocation.getAccuracy()) {
return true;
}
return false;
}
但是,如果我使用内置用户用户位置图层 - 它可以很好地工作 我错过了什么?
答案 0 :(得分:0)
我不确定这是否是问题,但在Android文档中显示并建议使用
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
// ... here is how I request the updates
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
连接Google客户端后。
除此之外,我没有发现任何特殊错误。
顺便说一句
您要求哪些权限?
您应该使用<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
代表LocationRequest.PRIORITY_HIGH_ACCURACY