我可能有一个简单的问题,但我不知道出了什么问题。
当我在地图上用按钮设置我的位置时,位置几乎是100个准确的。
当我使用位置管理器来获取我的位置时,我得到了大约10-20米的错误位置。
这是代码:
@Override
public void onMapReady(final GoogleMap googleMap) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGoogleMap = googleMap;
mGoogleMap.setMyLocationEnabled(true);
Button setLoc = (Button) findViewById(R.id.setLoc);
assert setLoc != null;
setLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGoogleMap.clear();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
latLng = new LatLng(location.getLatitude(), location.getLongitude());
Toast.makeText(MainActivity.this, String.valueOf(latLng), Toast.LENGTH_LONG).show();
//zoom to current position:
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
mGoogleMap.addMarker(new MarkerOptions().position(latLng).title("Your location").anchor(0.0f, 1.0f));
}
});
}
我做错了什么?蓝色点不在我的标记所在的位置,蓝色点的精度更好,如上所述。谢谢
小型更新当我在模拟器上运行代码时,它几乎在同一个位置。。。嗯,在实际设备上就不一样了。可能是什么问题?
我认为这可能与设备有关。您需要将优先级更改为PRIORITY_HIGH_ACCURACY
。在请求位置更新之前,您的应用程序必须连接到位置服务并发出位置请求。一旦位置请求到位,您可以通过在Google API客户端提供的onConnected()
回调中调用requestLocationUpdates()
来启动定期更新,该回调在客户端准备好时调用。
使用LocationListener回调更新位置。调用requestLocationUpdates()
,将您的GoogleApiClient实例、LocationRequest对象和LocationListener传递给它。定义一个从onConnected()
回调调用的startLocationUpdates()
方法。
@Override
public void onConnected(Bundle connectionHint) {
...
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}