[英]Can't find user location Google Maps Api v2
我需要找到当前的经度和纬度才能获取地址,但是它无法正常工作。
这是我的看法:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
我的Java代码:
public void GetCurrentLocal() throws IOException{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
System.out.println(address);
}
谢谢。
如果在myLocation.getLatitude();
上失败myLocation.getLatitude();
正如您在评论中提到的那样,则意味着locationManager.getLastKnownLocation(provider);
不会返回最后一个已知位置,因为它没有一个位置,因此它返回null,这就是您遇到NullPointerExeception
错误的原因。 在这种情况下,您需要实现LocationListener
并在至少收到一个位置更新后运行此方法。
要实现LocationListener
,可以检查以下示例:
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
我想这本阅读材料也可能对您很方便:
http://android-developers.blogspot.de/2011/06/deep-dive-into-location.html
我有此代码,对我来说有效
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;
}
Location location = this.getMyLocation();
LatLng locationGPS = new LatLng(location.getLatitude(), location.getLongitude());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.