我正在开展谷歌地图活动。我正在尝试获取当前location.it在模拟器上完美运行但没有获取我手机上的当前位置。这是我在我的应用程序中使用的代码...
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
Constants.lat = String.valueOf(lat);
Constants.lng = String.valueOf(lng);
}
常量是我已经对所声明的纬度和经度静态变量进行十分转换的类。这段代码写在一个函数中,它是从onCreate方法调用的。我每次都得到null位置。我在manifestfile中也声明了下面的代码。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
有人可以帮帮我吗?谢谢 。
答案 0 :(得分:1)
从文档中试用此代码。
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
在onCreate
中调用此功能。希望有所帮助。