[英]Zoom on current user location displayed
I'm using the Google Maps for Android v2. 我正在使用Android版Google Maps v2。 I would like to display the current user location and zoom on it. 我想显示当前用户位置并放大它。 Here is the code in the FragmentActivity
: 这是FragmentActivity
的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapFragment_mapActivity)).getMap();
if (mMap == null) {
Toast.makeText(this, R.string.mapCreationProblem, Toast.LENGTH_LONG)
.show();
finish();
return;
}
mMap.setMyLocationEnabled(true);
Location currentLocation = mMap.getMyLocation();
if(currentLocation!=null){
LatLng currentCoordinates = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 10));
}
}
The map works fine and also the blue dot on the current location works. 该地图可以正常工作,并且当前位置上的蓝点也可以正常工作。 But it seems currentLocation
is always null. 但似乎currentLocation
始终为null。 So I cannot zoom on the current location. 因此,我无法缩放当前位置。
Anyone who knows why, please? 知道为什么的人吗?
Here is an implementation of getMyLocation() with added protection for finding the persons location. 这是getMyLocation()的实现,其中添加了用于查找人员位置的保护。 I just have this in the activity that manages the map fragment. 我只是在管理地图片段的活动中拥有此功能。
private Location getMyLocation() {
// Get location from GPS if it's available
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Location wasn't found, check the next most accurate place for the current location
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
// Finds a provider that matches the criteria
String provider = lm.getBestProvider(criteria, true);
// Use the provider to get the last known location
myLocation = lm.getLastKnownLocation(provider);
}
return myLocation;
}
Thanks, DMan 谢谢DMan
Try using the LocationManager: 尝试使用LocationManager:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location currentLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.