簡體   English   中英

找不到用戶位置Google Maps Api v2

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM