获取用户当前位置的代码:然后将照相移到那个位置:
private void updatePlaces(){
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
}
如何徐改这个代码以便能获取新的位置,然后再用照相机进行比较?
为了获取新的位置,您可以使用 requestLocationUpdates() 方法。这个方法会告诉 LocationManager 持续监听位置更新。
例如,您可以在 updatePlaces() 方法中添加以下代码以便获取新的位置:
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// Get the new location
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
// Update the marker and camera
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
}
// other required methods
});
如果您不再需要监听位置更新,可以使用 removeUpdates() 方法取消监听。
为了比较照片,您可以将新的位置与上一个位置进行比较,如果它们之间的距离超过了某个阈值,就可以确定用户已经移动了。可以使用 Location 类中的 distanceBetween() 方法来计算两个位置之间的距离。