java根据地址获取百度API经纬度(详细文档)
1 public void getLarLng(String address) throws Exception { 2 3 String ak = "vZ5wAkH9uc6mCnrhtYWey2fBHBmU9Rh5"; 4 5 String addressUrl = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + ak + "&callback=showLocation"; 6 7 URL url = new URL(addressUrl); 8 9 InputStream inputStream = url.openStream(); 10 11 String string = IOUtils.toString(inputStream); 12 13 // showLocation&&showLocation({"status":0,"result":{"location":{"lng":121.4423987575458,"lat":30.939981749234133},"precise":1,"confidence":80,"level":"道路"}}) 14 15 System.out.println(string); 16 17 int len = string.length(); 18 19 String substring = string.substring(27, len - 1); 20 21 // {"status":0,"result":{"location":{"lng":121.4423987575458,"lat":30.939981749234133},"precise":1,"confidence":80,"level":"道路"}} 22 System.out.println(substring); 23 24 JSONObject jsonObject = JSONObject.parseObject(substring); 25 26 String status = jsonObject.getString("status"); 27 28 Double lng = 0.0; 29 30 Double lat = 0.0; 31 32 if (status.equals("0")){ 33 34 lng = jsonObject.getJSONObject("result").getJSONObject("location").getDouble("lng"); 35 36 lat = jsonObject.getJSONObject("result").getJSONObject("location").getDouble("lat"); 37 } 38 39 if (Double.isNaN(lng)){ 40 System.out.println(0); 41 } 42 BigDecimal bd = new BigDecimal(lng); 43 // 保留小数点后六位 并做四舍五入 44 double v = bd.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue(); 45 46 System.out.println(v); 47 System.out.println(lat); 48 }