Baidu api usage method (java, js)

Posted by jasonc on Sun, 19 May 2019 08:21:04 +0200

My own project used Baidu Map api, I will explain the part I used. First, let's look at a few websites. http://lbsyun.baidu.com/ This is the home page of Baidu Map Open Platform. http://lbsyun.baidu.com/index.php?title=jspopular/openlibrary This is the home page of the javascript docking Baidu Map api. http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding This is the home page of the web service (including address resolution and reverse address resolution) http://lbsyun.baidu.com/jsdemo.htm#i7_2 This is the source code of calling Baidu Map api example with js.     http://lbsyun.baidu.com/apiconsole/key This is the website for creating ak. But you have to pay for using foreign address resolution.

Next, we start the first step, creating ak. We need to use Baidu Map's api. First, we have to create an AK (that is, key) by ourselves. Different applications need to create different ak. Click application

Because I use in browser, so I choose the application type of browser side, the following start-up service describes what services can be used, I need to use js to call Baidu Map, so this is what I need, we can also see from here whether the application type we selected is correct.

The second step is to study several websites uploaded by me. For my website, I only use address resolution and call Baidu Map with js. That is to enter a detailed address, convert it into geographic coordinates or display it directly as a map.

This is a case web address for yes: http://api.map.baidu.com/geocoder/v2/? Address=10 Shangdi Tenth Street, Haidian District, Beijing&output=json&ak=your ak&callback=showLocation//GET request. Opening this web address may give us the coordinates of 10th Street on Beijing City Haidian, but to change to our ak, we can change the parameters of addressTo get The coordinates you want. The following are the parameters described.

 

Request parameters

Parameter name Parameter implication type Give an example Default value Is it necessary?
address The address to be resolved. Up to 84 bytes are supported.
Two types of values can be entered, namely:
1. Standard structured address information, such as 10 Shangdi 10th Street, Haidian District, Beijing [Recommendation, the more complete the address structure, the higher the resolution accuracy]
2. Supporting the description of "intersection of * road and * road", such as the intersection of North First Ring Road and Fuyang Road
The second method does not always have a return result, only when the address description exists in the address library.
string 10 Shangdi 10th Street, Beijing City Haidian District nothing yes
city The name of the city where the address is located. This parameter is used to specify the city where the above address is located. When multiple cities have the above address, this parameter acts as a filter, but does not restrict coordinate recall of the city. string Beijing nothing no
ret_coordtype Optional parameters are added and returned to the longitude and latitude coordinates of the National Bureau of Surveying or Baidu metre coordinates. Description of coordinate system string gcj02ll (National Bureau of Survey coordinates), bd09mc (Baidu Mercator coordinates) bd09ll (longitude and latitude coordinates of Baidu) no
ak User's key for registration has been changed to "ak" since v2 and "key" in previous versions. Application for ak string   nothing yes
sn If the check mode of ak used by the user is sn check, the parameter must be
sn generation
string   nothing no
output The output format is json or xml string json or xml xml no
callback Returning the return value of json format through callback function to realize jsonp function string callback=showLocation(JavaScript function name) nothing no

Return result parameters

Name Meaning type
status Returns the result status value and successfully returns 0. For other values, please see the return code status table below. int
location Longitudinal and latitudinal coordinates object
  lat Latitude value float
  lng Longitude value float
precise Additional information about the location, whether to find it accurately or not. 1 is accurate search, that is, accurate dotting; 0 is inaccurate, that is, fuzzy dotting. int
confidence Describes the absolute accuracy of the dotting (i.e. the error range of coordinate points).
confidence=100, the absolute accuracy of analytical error is less than 20m.
confidence (> 90) and the absolute accuracy of analytical error is less than 50 m.
confidence (> 80) and the absolute accuracy of analytical error is less than 100 m.
confidence (> 75) and the absolute accuracy of analytical error is less than 200 m.
confidence (> 70) and the absolute accuracy of analytical error is less than 300 m.
confidence (> 60) and the absolute accuracy of analytical error is less than 500 m.
confidence (> 50) and the absolute accuracy of analytical error is less than 1000m.
confidence (> 40), the absolute accuracy of analytical error is less than 2000 m.
confidence (> 30) and the absolute accuracy of analytical error is less than 5000m.
confidence (> 25) and the absolute accuracy of analytical error is less than 8000m.
confidence (> 20) and the absolute accuracy of analytical error is less than 10 000 M.
int
comprehension Describe the degree of address comprehension. Score range is 0-100, the larger the score, the higher the service's understanding of address (it is recommended that this field be used as the criterion for judging the result of parsing).
When the comprehension value is the following, the corresponding accuracy is as follows:
comprehension=100, the probability of analytic error within 100 m is 91%, and the probability within 500 m is 96%.
comprehension (> 90), the probability of analytic error within 100 m is 89%, and the probability within 500 m is 96%.
comprehension (> 80), analytic error within 100 m probability is 88%, error within 500 m probability is 95%.
comprehension (> 70), analytic error within 100 m probability is 84%, error within 500 m probability is 93%.
comprehension (> 60), analytic error within 100 m probability is 81%, error within 500 m probability is 91%.
comprehension (> 50), analytic error within 100 m probability is 79%, error within 500 m probability is 90%.
// Parsing error: The coordinate position obtained by the geocoding service parsing the address, and the distance between the real location corresponding to the address.
int
level Accurately understood address types include: UNKNOWN, country, province, city, district, township, village, road, real estate district, business building, government agency, intersection, business circle, life service, leisure and entertainment, catering, hotel, shopping, finance, education, medical treatment, industrial park, tourist attractions, bus service, train station, long distance bus station, bridge. Parking lot/parking area, port/wharf, toll area/toll station, airport, toll office/toll station, gas station, green space, gate address string

 

Service Status Code

Return code English description Definition Common causes
0 ok normal Normal recall of service requests
1   Server internal error  
2 Parameter Invalid Illegal request parameters Spelling errors or missing necessary parameters (such as query and tag requests are not passed in)
3 Verify Failure Privilege Check Failed  
4 Quota Failure Quota Verification Failure The number of service calls on that day has exceeded the limit. Please go to API console Promotion (Please Priority) Developer Certification)
5 AK Failure ak does not exist or is illegal No ak parameter was passed in; ak was deleted (accessible) recycle bin Resumption);
101   Service disabled  
102   No white list or incorrect security code  
2xx   No authority  
3xx   Quota error  

I found an example on the internet. I forgot the address name, but it was a jar package error. I found the right one later. When using the j'son attack class, we depended on a jar package from Alibaba. The name is fastjson. There are many tutorials and introductions about it on the internet. Next we introduce the method of obtaining coordinate system through java.

Import maven dependencies:

<dependency>
		<groupId>commons-lang</groupId>
		<artifactId>commons-lang</artifactId>
		<version>2.5</version>
	</dependency>
	<dependency>
		<groupId>commons-beanutils</groupId>
		<artifactId>commons-beanutils</artifactId>
		<version>1.9.3</version>
	</dependency>
	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.2</version>
	</dependency>

		<dependency>
			<groupId>com.vaadin.external.google</groupId>
			<artifactId>android-json</artifactId>
			<version>RELEASE</version>
			<scope>compile</scope>
		</dependency>
<!--Use json Toolkit, developed by Alibaba-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.57</version>
		</dependency>

The second step is to give the front-end bean

import java.io.Serializable;

/**
 * Test java and Baidu api together, through the address to obtain longitude and latitude returned json class
 */
public class BaseResponse implements Serializable{
    private String data;
    private Boolean Success;
    private String ErrorMsg;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public Boolean getSuccess() {
        return Success;
    }

    public void setSuccess(Boolean success) {
        Success = success;
    }

    public String getErrorMsg() {
        return ErrorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        ErrorMsg = errorMsg;
    }

    @Override
    public String toString() {
        return "BaseResponse{" +
                "data='" + data + '\'' +
                ", Success=" + Success +
                ", ErrorMsg='" + ErrorMsg + '\'' +
                '}';
    }
}

Your own controller class:

//Getting latitude and longitude according to place names
    public  String loadJSON(String url) {

        StringBuilder json = new StringBuilder();
        try {
            log.info("11-2");
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {} catch (IOException e) {}
        return json.toString();
    }

    //Return value
    @GetMapping("/getCoordinate")
    @ResponseBody
    public BaseResponse  getCoordinate(String address) {
        BaseResponse response = new BaseResponse();
        log.info("1");
        try{
            log.info("2");
            if (address != null && !"".equals(address)) {
                log.info("3");
                address = address.replaceAll("\\s*", "").replace("#"," "Tung".
                String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=Iyv2Gax3s1PF0PR4DtvToePapxIOuj1Y";
                String json = loadJSON(url);
                log.info("json:{}",json);
                if (json != null && !"".equals(json)) {
                    com.alibaba.fastjson.JSONObject obj = JSON.parseObject(json);
                    if ("0".equals(obj.getString("status"))) {
                        //log.info(String.valueOf(obj.getJSONObject("result").getJSONObject("location").getDouble("lng")));
                        double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng"); // longitude
                        log.info(String.valueOf(lng));
                        double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat"); // latitude

                      /*This is a fixed decimal, here fixed 7 decimal, the return result is 40.057339
                        DecimalFormat df = new DecimalFormat("#.######");
                        String lng1 = df.format(lng);
                        String lat1 = df.format(lat);*/
                        response.setData("Longitude:"+lng+"Latitude:"+lat);
                        response.setSuccess(true);

                        return response;
                    }
                }
            }

        }catch (Exception e){
            response.setErrorMsg("No network");
        }
        return response;
    }

Step 3: In fact, step 2 and step 3 can choose one of them and see their own needs. You can get the map you want directly by inputting the address or latitude and longitude. This is the source code on the official website. This is to use address resolution to change the 10th Street of Shangdi District, Haidian District, Beijing into other addresses, and input your own ak key to display the map.

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family: Microsoft Yahei;}
	</style>
	<script type="text/javascript" src="http://Api. map. baidu. com/api? V = 2.0 & AK = your key "> </script>"
	<title>Address resolution</title>
</head>
<body>
	<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
	// API Function of Baidu Map
	var map = new BMap.Map("allmap");
	var point = new BMap.Point(116.331398,39.897445);
	map.centerAndZoom(point,12);
	// Create an instance of address resolver
	var myGeo = new BMap.Geocoder();
	// Display the address resolution results on the map and adjust the map view
	myGeo.getPoint("Shangdi 10th Street, Haidian District, Beijing", function(point){
		if (point) {
			map.centerAndZoom(point, 16);
			map.addOverlay(new BMap.Marker(point));
		}else{
			alert("The address you chose did not resolve to the result!");
		}
	}, "Beijing");
  map.enableScrollWheelZoom(true);     //Turn on the mouse wheel to zoom in
</script>

Because I have just used the Baidu Map api, so there are many things still not very clear, there is a chance to change slowly in the future.

Topics: JSON less Javascript xml