Java based on the address to obtain latitude and longitude (Baidu map)

Source: Internet
Author: User

Official parameter Description: http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding 1. Create application in Baidu map

Address: Http://lbsyun.baidu.com/apiconsole/key
2. Obtaining Signatures

According to the need we have to do the Java version of the calculation signature signature!! The AK that was created before is placed in the parameter

Import java.io.UnsupportedEncodingException;
Import Java.net.URLEncoder;
Import java.security.NoSuchAlgorithmException;
Import Java.util.LinkedHashMap;
Import Java.util.Map;

Import Java.util.Map.Entry; Java version Compute signature Signature public class Sncal {public static void main (string[] args) throws Unsupportedencodingexcepti

On, nosuchalgorithmexception {sncal sncal = new sncal (); To calculate the order of the SN and the parameters to occur, get requests use Linkedhashmap to save the <key,value&gt, which is sorted according to the key insertion order; Post please use TreeMap to save <key,value>, This method automatically sorts the key alphabetically by letter-A-Z order. So the GET request can customize the parameter order (the SN parameter must be at the last) to send the request, but the POST request must populate the body in the letter-A-Z order (the SN parameter must be at the end). Take request for example: http://api.map.baidu.com/geocoder/v2/?address= Baidu Mansion &output=json&ak=yourak,paramsmap first put address

                , then put the output, then put AK, put the order must be in the GET request of the corresponding parameters in the order of the occurrence of consistency.
                Map Paramsmap = new linkedhashmap<string, string> ();
                Paramsmap.put ("Address", "Baidu Mansion");
                Paramsmap.put ("Output", "json");

Paramsmap.put ("AK", "Yourak");                The following toquerystring method is invoked to encode all the value in the Linkedhashmap as UTF8, and the concatenation returns the result ADDRESS=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&A

                Mp;output=json&ak=yourak String paramsstr = sncal.toquerystring (Paramsmap); On the paramsstr front stitching on the/geocoder/v2/, the back of the direct stitching Yoursk get/geocoder/v2/?address=%e7%99%be%e5%ba%a6%e5%a4%a7%e5%8e%a6&

                Output=json&ak=yourakyoursk string wholestr = new String ("/geocoder/v2/?" + paramsstr + "Yoursk");

                The above wholestr is then UTF8 encoded String tempstr = Urlencoder.encode (Wholestr, "UTF-8");
        The following MD5 method is invoked to obtain the final SN signature 7de5a22212ffaa9e326444c75a58f9a0 System.out.println (SNCAL.MD5 (TEMPSTR));
                        ///UTF8 code for all value in Map, concatenation return result public String toquerystring (map<?,? > Data)
                Throws Unsupportedencodingexception {StringBuffer querystring = new StringBuffer ();
For (entry<?,? > Pair:data.entrySet ()) {                        Querystring.append (Pair.getkey () + "="); Querystring.append (Urlencoder.encode ((String) Pair.getvalue (), "UTF-8") + "&")
                ;  } if (Querystring.length () > 0) {querystring.deletecharat (Querystring.length ())
                -1);
        return querystring.tostring ();
                ////MD5 calculation method from StackOverflow, called MessageDigest library function, and converts byte array result to 16 binary public string MD5 (string md5) {
                                        try {java.security.MessageDigest MD = Java.security.MessageDigest
                        . getinstance ("MD5");
                        byte[] Array = md.digest (Md5.getbytes ());
                        StringBuffer sb = new StringBuffer (); for (int i = 0; i < Array.Length ++i) {sb.append (integer.tohexstring (array[i) & 0xFF) | 0x1). substring (1, 3));
                return sb.tostring ();
        catch (Java.security.NoSuchAlgorithmException e) {} return null; }
}

call Baidu Map interface using httpclient technology

Official parameter Description: http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

Import java.io.IOException;
Import java.util.ArrayList;

Import java.util.List;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.impl.client.HttpClients;
Import Org.apache.http.message.BasicNameValuePair;

Import Org.apache.http.util.EntityUtils; public class Allseagen {public static void main (string[] args) throws IOException {HttpClient client = Httpclients.createdefault ()///create default HTTP connection HttpPost post = new HttpPost ("http://api.map.baidu.com/geocoder/v2/"
            //Create a POST request list<namevaluepair> paramlist = new arraylist<namevaluepair> (); Paramlist.add (New Basicnamevaluepair ("AK", ""));//passed parameter Paramlist.add (new Basicnamevaluepair ("SN", "")); Number Paramlist.add (New BASICNAmevaluepair ("Address", "No. 10th, 10 Street, Haidian District, Beijing"));//Pass the parameter//insert the reference into the request entity httpentity Entitya = new Urlenc
            Odedformentity (Paramlist, "utf-8"); Post.setentity (Entitya)//To place the request entity in the POST request HttpResponse response = Client.execute (post);//To execute a GET request with an HTTP connection and obtain HT TP Response Httpentity entity = response.getentity ()//from response to sound entity String HTML = Entityutils.tostrin


        g (entity);//Turn response entity into text System.out.println (HTML);
 }
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.