PackageCn.stopgo.tool;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;Importjava.io.UnsupportedEncodingException;Importjava.net.MalformedURLException;ImportJava.net.URL;Importjava.net.URLConnection; Public classGetlatandlngbybaidu {/** * @paramAddr * Query Address *@return * @throwsIOException*/ PublicObject[] Getcoordinate (String addr)throwsIOException {String LNG=NULL;//LongitudeString lat =NULL;//LatitudeString address =NULL; Try{Address= Java.net.URLEncoder.encode (addr, "UTF-8"); }Catch(unsupportedencodingexception E1) {e1.printstacktrace (); } //String key = "F247CDB592EB43EBAC6CCD27F796E2D2";String key= "Cs1cfjkqbpd6lbeg7erspodt"; String URL= String. Format ("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key); URL Myurl=NULL; URLConnection Httpsconn=NULL; Try{Myurl=Newurl (URL); } Catch(malformedurlexception e) {e.printstacktrace (); } inputstreamreader INSR=NULL; BufferedReader BR=NULL; Try{httpsconn= (URLConnection) myurl.openconnection ();//do not use proxies if(Httpsconn! =NULL) {INSR=NewInputStreamReader (Httpsconn.getinputstream (), "UTF-8"); BR=NewBufferedReader (INSR); String Data=NULL; intCount = 1; while((Data= br.readline ())! =NULL){ if(count==5) {LNG= (String) data.subsequence (Data.indexof (":") +1, Data.indexof (","));//Longitudecount++; }Else if(count==6) {lat= Data.substring (Data.indexof (":") +1);//Latitudecount++; }Else{Count++; } } } } Catch(IOException e) {e.printstacktrace (); } finally { if(insr!=NULL) {insr.close (); } if(br!=NULL) {br.close (); } } return NewObject[]{lng,lat}; } Public Static voidMain (string[] args)throwsIOException {Getlatandlngbybaidu Getlatandlngbybaidu=NewGetlatandlngbybaidu (); Object[] o= Getlatandlngbybaidu.getcoordinate ("Tangshan"); System.out.println (o[0]);//LongitudeSystem.out.println (o[1]);//Latitude }}
Get latitude and longitude