简体   繁体   English

如何获取给定城市或地址名称的纬度和经度(java代码)?

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

I want to get latitude and longitude from a city name in java project(eclipse) with GoogleMaps.我想使用 GoogleMaps 从 java 项目(eclipse)中的城市名称获取纬度和经度。 I tried with this code but I find multiple errors.我尝试使用此代码,但发现多个错误。 I think because it is for Android.我认为是因为它适用于 Android。 I wonder if you can help me??我想知道你是否可以帮助我?

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

The code you've posted is indeed for Android as it's using Android's Geocoder class .您发布的代码确实适用于 Android ,因为它使用的是 Android 的地理编码器 class

If you're trying to geocode addresses server-side in a web application, then you should use the client libraries for web services instead.如果您尝试在 web 应用程序中对服务器端地址进行地理编码,则应改用web 服务的客户端库 The Java client can be found here and it provides the following code example for Geocoding API: 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));

Note that you'll need a valid API key;请注意,您需要一个有效的 API 密钥; I recommend you go through Google's get started guide .我通过 Google 的入门指南向您推荐 go。

Hope this helps you.希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM