簡體   English   中英

如何獲取給定城市或地址名稱的緯度和經度(java代碼)?

[英]how to get Latitude and Longitude of the given Name of the City or Address (java code)?

我想使用 GoogleMaps 從 java 項目(eclipse)中的城市名稱獲取緯度和經度。 我嘗試使用此代碼,但發現多個錯誤。 我認為是因為它適用於 Android。 我想知道你是否可以幫助我?

public boolean getLatitudeAndLongitudeFromGoogleMapForAddress(String searchedAddress){

    Geocoder coder = new Geocoder(IPlant.iPlantActivity);
    List<Address> address;
    try 
    {
        address = coder.getFromLocationName(searchedAddress,5);
        if (address == null) {
            Log.d(TAG, "############Address not correct #########");
        }
        Address location = address.get(0);

        Log.d(TAG, "Address Latitude : "+ location.getLatitude();+ "Address Longitude : "+ location.getLongitude());
        return true;

    }
    catch(Exception e)
    {
        Log.d(TAG, "MY_ERROR : ############Address Not Found");
        return false;
    }
}

您發布的代碼確實適用於 Android ,因為它使用的是 Android 的地理編碼器 class

如果您嘗試在 web 應用程序中對服務器端地址進行地理編碼,則應改用web 服務的客戶端庫 Java 客戶端可以在這里找到,它提供了以下代碼示例用於地理編碼 API:

GeoApiContext context = new GeoApiContext.Builder()
    .apiKey("AIza...")
    .build();
GeocodingResult[] results =  GeocodingApi.geocode(context,
    "1600 Amphitheatre Parkway Mountain View, CA 94043").await();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(results[0].addressComponents));

請注意,您需要一個有效的 API 密鑰; 我通過 Google 的入門指南向您推薦 go。

希望這對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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