SoFunction
Updated on 2025-03-01

Steps to convert latitude and longitude into geolocation information using Java and the Gaode Map API

Preface

When developing applications involving map and location services, converting the latitude and longitude coordinates provided by GPS devices into human-readable geographical locations is a common requirement. This article will introduce in detail how to implement this function using the Java language and the Gaode Map API, including environment preparation, code implementation, exception handling, and code optimization.

Development environment preparation

  • Java environment: Make sure that Java is installed in your development environment.
  • Gaode Map API Key: Visit the Gaode Map Open Platform, register and apply for API keys.

Step 1: Create a Java class

First, create aLocationFinderJava class. This class contains a main methodmainUsed to call the position conversion function and includegetLocationFromCoordinatesThe method is used to achieve the conversion of latitude and longitude to geographic location.

public class LocationFinder {
    public static void main(String[] args) {
        String longitude = "115.658755"; // Longitude        String latitude = "38.961134";   // Latitude        String apiKey = "Your API Key";  // Gaode Map API Key
        try {
            String location = getLocationFromCoordinates(longitude, latitude, apiKey);
            ("Geographical Location: " + location);
        } catch (Exception e) {
            ();
            ("Geolocation resolution failed");
        }
    }
}

Step 2: Implement the position conversion function

getLocationFromCoordinatesThe inverse geocoding API of Gaode Map is used in the method. This method initiates an HTTP GET request to the Gaode server by building a URL with API key and location parameters. The received response is data in JSON format, and we use the Gson library to parse this data to extract provincial, municipal and regional information.

import ;
import ;
import ;
import ;
import ;

public static String getLocationFromCoordinates(String longitude, String latitude, String apiKey) {
    String url = "/v3/geocode/regeo?key=" + apiKey + "&location=" + longitude + "," + latitude;
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        ("GET");
        reader = new BufferedReader(new InputStreamReader(()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = ()) != null) {
            (line);
        }

        Gson gson = new Gson();
        GaoDeDTO gaoDeDTO = ((), );
         addressComponent = ().getAddressComponent();
        String province = ();
        String cityStr = getStringFromObject(());
        String districtStr = getStringFromObject(());

        return province + cityStr + districtStr;
    } catch (Exception e) {
        return "Overseas address, cannot be resolved";
    } finally {
        if (reader != null) {
            try {
                ();
            } catch (Exception e) {
                ();
            }
        }
        if (connection != null) {
            ();
        }
    }
}

 // Get string from objectprivate static String getStringFromObject(Object obj) {
   if (obj instanceof String) {
       return " " + (String) obj;
   } else if (obj instanceof List) {
       List<String> list = (List<String>) obj;
       if (!()) {
           return " " + (0);
       }
   }
   return "";
}
/**
 * @author lxy
 * @date 2024/5/13
 */
@NoArgsConstructor
@Data
public class GaoDeDTO {
    @JsonProperty("info")
    private String info;
    @JsonProperty("infocode")
    private String infocode;
    @JsonProperty("regeocode")
    private RegeocodeDTO regeocode;
    @JsonProperty("status")
    private String status;

    @NoArgsConstructor
    @Data
    public static class RegeocodeDTO {
        @JsonProperty("addressComponent")
        private AddressComponentDTO addressComponent;
        @JsonProperty("formatted_address")
        private String formattedAddress;

        @NoArgsConstructor
        @Data
        public static class AddressComponentDTO {
            @JsonProperty("adcode")
            private String adcode;
            @JsonProperty("city")
            private Object city;
            @JsonProperty("citycode")
            private String citycode;
            @JsonProperty("country")
            private String country;
            @JsonProperty("district")
            private Object district;

            @JsonProperty("province")
            private String province;
            @JsonProperty("towncode")
            private String towncode;
            @JsonProperty("township")
            private String township;


        }
    }
}

Step 3: Exception handling

We ensure the robustness of the program through exception handling, catch and handle possible exceptions. When there is a problem with network request or JSON resolution, the program will output "Overseas address, cannot be resolved".

Main code tuning and optimization

  • Code Refactoring: Passing the API key as a method parameter increases code flexibility.
  • JSON parsing using Gson: Replace the original manual parsing method and use the Gson library to automatically map JSON to Java objects, simplifying the code and improving maintainability.
  • Enhanced exception handling:Exception handling of network requests and JSON parsing is enhanced to ensure that the program can correctly close the resources and give clear error information when an error occurs.

Test run

runmainMethod, the output should display the provincial, municipal and district information of the specified coordinates, such as: "Qingyuan District, Baoding City, Hebei Province".

Conclusion

Through the above steps, you can easily implement latitude and longitude to geolocation conversion in any Java application. This is very useful for developing geographic information systems (GIS), location services, or any application that requires geocoding. Hope this tutorial will help you implement position conversion function in your project.

Attachment: Java uses Gaode map to parse the city where the latitude and longitude string is located

public class LocationUtil {
	/**
	  * Analyze city information through address location information
	  * @param location Geographic information, format Longitude, latitude
	  * 114.05,22.55
	  * @return
	  */
	public static String parseLocation(String location){
		// /api/webservice/guide/api/georegeo Inverse address resolution		// amap_api Register Gaode Map Developer, create an application, and obtain apikey		//Test key: 8f21643950153e066e4bfefc3d244e19		String amap_api_key = "You need to fill in the Gaode map apiKey here";
		String url = "/v3/geocode/regeo?key="+amap_api_key+"&"+"location="+location;
		String jsonData =  (url);
		JSONObject jsonLocation = (jsonData);
		String city = "";
		if("1".equals(("status"))){
			JSONObject addressComponent =("regeocode").getJSONObject("addressComponent");
			Object obj = null;
			// If it is a municipality, city returns data			if((obj = ("city")) instanceof String){
				city=  (String)obj;
			}else if ((obj = ("province")) instanceof String){
				// If it is a municipality, return data through province				city= (String)obj;
			}
			city = ("city","");
		}
		return city;
	}
}

This is the article about converting latitude and longitude into geographical location information using Java and Gaode Map API. For more relevant content on converting latitude and longitude into geographical location, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!