找不到用户位置Google Maps Api v2

时间:2013-08-08 17:27:05

标签: java android google-maps latitude-longitude google-maps-api-2

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

这是我的意思:

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

感谢。

2 个答案:

答案 0 :(得分:3)

如果它在评论中提到的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

答案 1 :(得分: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());