问题描述
我使用的是谷歌地图Android版V2。我想显示当前用户的位置,并放大就可以了。这里是code。在 FragmentActivity
:
I'm using the Google Maps for Android v2. I would like to display the current user location and zoom on it.Here is the code in the 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));
}
}
地图工作正常,也是蓝点的当前位置的作品。但似乎 currentLocation
总是空。因此,我不能放大的当前位置。
The map works fine and also the blue dot on the current location works. But it seems currentLocation
is always null. So I cannot zoom on the current location.
任何谁知道这是为什么吗?
Anyone who knows why, please?
推荐答案
下面是getMyLocation的)与寻找的人的位置额外保护的实现(。我只是有这个在管理该地图碎片的活动。
Here is an implementation of getMyLocation() with added protection for finding the persons location. 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;
}
谢谢,DMAN
Thanks,DMan
这篇关于放大当前用户位置显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!