我想在 Google Maps Android API v2 中启用位置。我想要的是:
- 加载以固定纬度/经度为中心的 map 。
- 开始监听位置变化,一旦提供商(网络/GPS)获取位置,将 map 置于该位置的中心并为其设置动画(动画只能运行一次)。同时,位置监听器会在指定时间后更新用户的位置,
- 存储此位置数据并通过我的 API 使用它来获取附近的景点。
我对如何获取定期更新、选择的时间间隔量感到有点困惑。现在,我已经设置了显示 map 的项目并使用了
googleMap.setMyLocationEnabled(true);
googleMap.setOnMyLocationChangeListener(myLocationChangeListener);
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
if(googleMap != null){
if(!firstTime){
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(loc).zoom(zoom).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
firstTime = true;
}
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(context, "Location is: " + String.valueOf(lat) + ", "
+ String.valueOf(lng), Toast.LENGTH_LONG).show();
}
}
};
在变量中设置纬度/经度。 我的问题是:
- 这是正确的方法吗?或者可以做得更好吗?
- 位置更改监听器经常自行更新。我看到在几秒钟的间隔内就进行了 toast 。如何监管?
- 当 Activity 消失(暂停/停止)时,如何阻止监听器获取位置? 谢谢!
最佳答案
对于问题 2:
使用requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntentintent)
前两个参数是:
参数 minTime :位置更新之间的最小时间间隔,以毫秒为单位 minDistance :位置更新之间的最小距离,以米为单位
private static final long POLLING_FREQ = 1000 * 10;
private static final float MIN_DISTANCE = 10.0f;
// Reference to the LocationManager and LocationListener
private LocationManager mLocationManager;
private LocationListener mLocationListener;
// Register for network location updates
if (null != mLocationManager
.getProvider(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, POLLING_FREQ,
MIN_DISTANCE, mLocationListener);
}
// Register for GPS location updates
if (null != mLocationManager
.getProvider(LocationManager.GPS_PROVIDER)) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, POLLING_FREQ,
MIN_DISTANCE, mLocationListener);
}
您可以根据自己的需要进行调整。
对于问题 3:
使用:removeUpdates(PendingIntentintent)
删除指定待处理 Intent 的所有位置更新。
从问题 1 开始。
你的做法看起来很合理。如果您需要不断的位置更新,如果不需要,那么我可以建议其他方法来减少电池消耗。
mLocationListener = new LocationListener() {
// Called back when location changes
public void onLocationChanged(Location location) {
// Get your location here
// estimate
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// NA
}
public void onProviderEnabled(String provider) {
// NA
}
public void onProviderDisabled(String provider) {
// NA
}
};
关于android - 如何在 Google Maps Android API V2 中获取位置及其更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26636972/