-1

我需要找到当前的纬度和经度来获取地址,但它不起作用。

这是我的许可:

<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);
}

谢谢。

4

2 回答 2

3

如果它myLocation.getLatitude();如您在评论中提到的那样失败,那么这意味着它locationManager.getLastKnownLocation(provider);不会返回最后一个已知位置,因为它没有一个,所以它返回 null,这就是您NullPointerExeception出错的原因。在这种情况下,您需要实现 aLocationListener并在收到至少一个位置更新后运行此方法。

要实施LocationListener,您可以检查此示例:

http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

我想这个阅读材料对你来说也很方便:

http://android-developers.blogspot.de/2011/06/deep-dive-into-location.html

于 2013-08-08T17:58:25.477 回答
0

我有这个代码,对我有用

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());
于 2013-08-08T18:32:10.267 回答