Query longitude and latitude according to address

1. Query longitude and latitude according to address

1.1. Gaode map

It is recommended to use this. There are more free times per day and the concurrency is high

public Map<String, Object> getLatAndLngByAddress(String addr) {
        String address = "";
        try {
            address = java.net.URLEncoder.encode(addr,"UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
		//The key here can be applied on the official website of Gaode map. Don't use mine. (I deleted several of this key and can't let you use it)
        String url =  "https://restapi.amap.com/v3/geocode/geo?address= "+address + "&output=JSON&key=" + "1cc533db4482c9bc9daece853e2";

        URL myURL = null;
        URLConnection httpsConn = null;
        //Transcoding
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {

        }
        StringBuffer sb = new StringBuffer();
        try {
            httpsConn = (URLConnection) myURL.openConnection();
            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                while ((data = br.readLine()) != null) {
                    sb.append(data);
                }
                insr.close();
            }
        } catch (IOException e) {

        }
        Map<String, Object> map = new HashMap<String, Object>();
    	//This is the data in json format
        JSONObject resultJson = JSON.parseObject(sb.toString());

        //Get longitude and latitude json data from Gaode map, exchange object and Array, and use Alibaba's package com alibaba. fastjson. json / jsonobject / jsonarray import package
        JSONArray geocodes = resultJson.getJSONArray("geocodes");
        JSONObject jsonObject = geocodes.getJSONObject(0);
        String location = jsonObject.getString("location");  //Longitude and latitude
        String district = jsonObject.getString("district");  //region

        String lng = StringUtils.substringBefore(location, ",");
        String lat = StringUtils.substringAfter(location, ",");

        map.put("lat", lat);
        map.put("lng", lng);
        map.put("area",district);
        return map;
    }
  • Geocoding API service address
URLhttps://restapi.amap.com/v3/geocode/geo?parameters
Request modeGET
  • Request parameters
Parameter namemeaningRule descriptionIs it necessaryDefault value
keyGaode KeyUsers on the official website of Gaode map Request Web Service API type KeyRequirednothing
addressStructured address informationRules: country, province, city, District, county, town, village, street, house number, real estate and building, such as No. 6, Futong East Street, Chaoyang District, Beijing. If you need to resolve multiple addresses, please use "|" for interval, and set the batch parameter to true. Requests in the form of "|" segmentation are supported for up to 10 addresses.Requirednothing
citySpecify the city for the queryOptional inputs include: Chinese of the specified city (e.g. beijing), Chinese spelling of the specified city (beijing), citycode (010), and adcode (110000). County level cities are not supported. When the query content of the specified city is empty, nationwide address translation retrieval will be carried out. For information on adcode, please refer to City code table obtainOptionalNo, nationwide search will be conducted
batchBatch query controlBatch query is performed when the batch parameter is set to true. Batch query is supported for up to 10 addresses. When the batch parameter is set to false, a single point query is performed. At this time, even if multiple addresses are passed in, only the resolution query result of the first address is returned.Optionalfalse
sigdigital signature Please refer to Digital signature acquisition and use methodOptionalnothing
outputReturn data format typeOptional inputs include JSON and XML. Set JSON, and the returned result data will be composed of JSON structure; If XML is set, the returned result data will be composed of XML structure.OptionalJSON
callbackCallback functionThe callback value is the user-defined function name. This parameter is only valid when the output parameter is set to JSON.Optionalnothing
  • Return parameters
namemeaningRule description
statusThe return value is 0 or 1. 0 indicates that the request failed; 1 indicates that the request was successful.
countNumber of returned resultsNumber of returned results.
infoReturn status descriptionWhen status is 0, info will return the specific error reason, otherwise it will return "OK". For details, please refer to info status table
geocodesGeocoding information listResult object list, including the following fields:
formatted_addressStructured address informationProvince + city + district / county + town + village + street + house number
countrycountryThe domestic address returns to China by default
provinceName of the province where the address is locatedFor example: Beijing. It should be noted here that China's four municipalities directly under the central government are also counted as provincial units.
cityCity name of addressFor example: Beijing
citycodeCity CodeFor example: 010
districtAddress areaFor example: Chaoyang District
streetstreetFor example: Futong East Street
numberHouse numberFor example: No. 6
adcodeArea codingFor example: 110101
locationCoordinate pointLongitude, latitude
levelMatch levelSee the list of geocoding matching levels below

1.2 Baidu map

public Map<String, Object> getLatAndLngByAddress(String addr) {
    String address = "";
    try {
        address = java.net.URLEncoder.encode(addr,"UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

	//For ak here, you can apply on the official website of Baidu maps. Don't use mine (I deleted several of this ak and can't let you use it)
    String url = "http://api.map.baidu.com/geocoding/v3/?address="+ address + "&output=json&ak=" + "oKdLH6xcnuIeGvfuDwrYwyUH";

    URL myURL = null;
    URLConnection httpsConn = null;
    //Transcoding
    try {
        myURL = new URL(url);
    } catch (MalformedURLException e) {

    }
    StringBuffer sb = new StringBuffer();
    try {
        httpsConn = (URLConnection) myURL.openConnection();
        if (httpsConn != null) {
            InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
            BufferedReader br = new BufferedReader(insr);
            String data = null;
            while ((data = br.readLine()) != null) {
                sb.append(data);
            }
            insr.close();
        }
    } catch (IOException e) {

    }
    Map<String, Object> map = new HashMap<String, Object>();
    JSONObject resultJson = JSON.parseObject(sb.toString());

    //Baidu map to obtain latitude and longitude
    JSONObject jsonArray = (JSONObject)resultJson.get("result");
    JSONObject locationObj = (JSONObject)jsonArray.get("location");
    //longitude
    String lng = (String)locationObj.get("lng");
    //latitude
    String lat = (String)locationObj.get("lat");

    map.put("lat", lat);
    map.put("lng", lng);
    return map;
}
  • Geocoding
http://api.map.baidu.com/geocoding/v3/?address = No. 10, Shangdi 10th Street, Haidian District, Beijing & output = JSON & AK = your AK & callback = showlocation / / get request
//Note: currently v3 Version 0 interface document, v2 0 and previous versions cannot be used by new users since June 18, 2019. Old users can still use v2 0 and earlier versions request the implementation of reverse geocoding service. In order to ensure the user experience, it is recommended that you migrate to V3.0 as soon as possible Version 0.
  • Request parameters
Parameter nameParameter meaningtypegive an exampleDefault valueIs it necessary
addressAddress to be resolved. Up to 84 bytes are supported. Two types of values can be entered: 1. Standard structured address information, [recommended, the more complete the address structure is, the higher the resolution accuracy] 2. The "road to road intersection" description method is supported. The second method does not always return results. It can only be returned when the address description exists in the address library.string10 Shangdi 10th Street, Haidian District, Beijingnothingyes
cityThe name of the city where the address is located. Used to specify the city where the above address is located. When multiple cities have the above address, this parameter plays the role of filtering, but does not limit the coordinate recall city.stringBeijingnothingno
ret_coordtypeOptional parameters, after adding, return to the longitude and latitude coordinates of the National Survey Bureau or Baidu metric coordinates Coordinate system descriptionstringgcj02ll (coordinates of China National Survey Bureau), bd09mc (coordinates of Baidu Mercator)bd09ll (Baidu latitude and longitude coordinates)no
akThe parameter of the key applied for registration by the user has been changed to "ak" since v2, and the parameter of the previous version is "key" Application akstringnothingyes
snIf the verification method of ak used by the user is sn verification, this parameter must be sn generationstringnothingno
outputThe output format is json or xmlstringjson or xmlxmlno
callbackReturn the return value in json format through the callback function to realize the json functionstringcallback=showLocation(JavaScript function name)nothingno
  • Return result parameters
namemeaningtype
statusThe result status value is returned. 0 is returned successfully. For other values, please see the return code status table below.int
locationLongitude and latitude coordinatesobject
latLatitude valuefloat
lngLongitude valuefloat
preciseAdditional information on location, whether to find it accurately. 1 for accurate search, i.e. accurate management; 0 is imprecise, i.e. fuzzy dot.int
confidenceDescribe the absolute accuracy of dot (i.e. the error range of coordinate points).int
comprehensionDescribe the level of understanding of the address. The score range is 0-100. The higher the score, the higher the service's understanding of the address (it is recommended to use this field as the judgment standard for the analysis result);
//Parsing error: the distance between the coordinate position obtained by the geocoding service parsing the address and the real position corresponding to the address.
int
levelAddress types that can be accurately understood include: UNKNOWN, country, province, city, district and county, township, village, road, real estate community, business building, government agency, intersection, business district, life service, leisure and entertainment, catering, hotel, shopping, finance, education, medical treatment, Industrial Park, tourist attraction, bus service, railway station, long-distance bus station, bridge Parking lot / parking area, port / wharf, toll area / toll station, airport, airport, toll office / toll station, gas station, green space, door addressstring

If it works for you, just praise it

Keywords: Java JSON

Added by Rocu on Tue, 25 Jan 2022 05:41:30 +0200