2017-03-06 88 views
0

我是一名初學者程序員,在大學讀過幾門課程,因此對該領域沒有完整的理解。我想我會用GoogleMaps API編碼一個android應用程序,並發現需要將用戶輸入的地址(以字符串格式)轉換爲Google的補充LatLng類,或更確切地說,提取緯度和經度座標爲了輸入到LatLng的構造函數(JAVA)。地理編碼 - 將地址(以字符串形式)轉換爲Google地圖Java中的LatLng

我在網上搜索的問題幾乎沒有結果,因爲在線代碼建議很複雜,因爲現在的問題是一個非常標準的問題。我想到GoogleMaps API中可能有一個功能可以讓我這樣做,但我找不到它。對於我們這裏的初學者來說,有關我如何做到這一點的任何指示?

回答

4

您需要使用Geocoder。試試這個代碼片段:

public LatLng getLocationFromAddress(Context context, String inputtedAddress) { 

    Geocoder coder = new Geocoder(context); 
    List<Address> address; 
    LatLng resLatLng = null; 

    try { 
     // May throw an IOException 
     address = coder.getFromLocationName(inputtedAddress, 5); 
     if (address == null) { 
      return null; 
     } 

     if (address.size() == 0) { 
      return null; 
     } 

     Address location = address.get(0); 
     location.getLatitude(); 
     location.getLongitude(); 

     resLatLng = new LatLng(location.getLatitude(), location.getLongitude()); 

    } catch (IOException ex) { 

     ex.printStackTrace(); 
     Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show(); 
    } 

    return resLatLng; 
} 
+0

偉大的人,爲我工作 –

相關問題