2015-09-30 35 views
0

我想在我的應用程序中使用Geocoder類,並發現Geocoder.getFromLocationName返回null,如果地址是兩條街道的交集。防爆。 「Quail Ave和Dunford Way,Sunnyvale,CA 94087」。但是,該方法適用於任何其他類型的地址。 在調試會話期間,我可以看到地址參數傳遞並正確反映,但「geocodeMatches」返回大小(0)零。 欣賞任何幫助!Geocoder.getFromLocationName不適用於交叉地址

public static List<Address> getGeoCode(@NonNull Context context, @NonNull String address){ 
    try { 
     geocodeMatches = new Geocoder(context).getFromLocationName(address, 1); 

     if (!geocodeMatches.isEmpty()) 
     { 
      return geocodeMatches; 
     } 

    } catch (IOException e) { 
     Log.e("ERROR", "Error to retrieve geocode" + e); 
     e.printStackTrace(); 
    } 
    return geocodeMatches; 
} 

回答

1

GeoCoder正在使用NetworkLocationService。在某些情況下,NetworkLocationService由於某種原因停止工作。我不知道確切的原因。但在這種情況下,您可以從google api獲取地址。 希望下面的代碼將幫助你!

public static String GetLocationAddressFromLatLong(Context context, double latitude, double longitude) { 
    String finalAddress = ""; 
    Geocoder geocoder; 
    List<Address> addresses = null; 
    geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault()); 
    try { 
     addresses = geocoder.getFromLocation(latitude, longitude, 1); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    if (addresses != null && addresses.size() > 0) { 
     finalAddress = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1); 
    } else { 
     //Get address from Google api 
     try { 
      JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," 
        + longitude + "&sensor=true"); 
      String Status = jsonObj.getString("status"); 
      if (Status.equalsIgnoreCase("OK")) { 
       JSONArray Results = jsonObj.getJSONArray("results"); 
       JSONObject location = Results.getJSONObject(0); 
       finalAddress = location.getString("formatted_address"); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
    return finalAddress; 
} 
+0

謝謝Banty Patel,我會盡力實現這一點,並讓你知道它是如何發生的。 – Babs

+0

你有沒有試過這個@Babs?讓我知道是否需要更多幫助。謝謝。 –

+0

非常感謝Banty Patel,我嘗試了你的建議,並且能夠從google maps api中獲得JSON響應。 – Babs

相關問題