1 protected void runTest() throws Throwable { 2 3 try { 4 BaiduLocation bl = new BaiduLocation(); 5 bl.gpsx = 120;//经度 6 bl.gpsy = 30;//纬度 7 GetBaiduLocation(bl); 8 if(bl.ok) { 9 int baidux = (int)(bl.baidux*1E6); 10 int baiduy = (int)(bl.baiduy*1E6); 11 // 转换成功,这个坐标是百度专用的 12 } 13 else { 14 /// 转换失败 15 } 16 } 17 catch(Exception ex) { 18 } 19 } 20 21 class BaiduLocation { 22 public float gpsx, gpsy; 23 public float baidux, baiduy; 24 public boolean ok = false; 25 } 26 27 public static String GetBaiduLocation(float x, float y) throws MalformedURLException, IOException { 28 String url = String.format("http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=%f&y=%f", x, y); 29 HttpURLConnection urlConnection = (HttpURLConnection)(new URL(url).openConnection()); 30 urlConnection.connect(); 31 BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 32 String lines = reader.readLine(); 33 reader.close(); 34 urlConnection.disconnect(); 35 return lines; 36 } 37 38 public static boolean GetBaiduLocation(BaiduLocation bl) { 39 try { 40 bl.ok = false; 41 String res = GetBaiduLocation(bl.gpsx, bl.gpsy); 42 if(res.startsWith("{") && res.endsWith("}")) { 43 res = res.substring(1, res.length() - 2).replace("\"", ""); 44 String[] lines = res.split(","); 45 for(String line : lines) { 46 String[] items = line.split(":"); 47 if(items.length == 2) { 48 if("error".equals(items[0])) { 49 bl.ok = "0".equals(items[1]); 50 } 51 if("x".equals(items[0])) { 52 bl.baidux = ConvertBase64(items[1]); 53 } 54 if("y".equals(items[0])) { 55 bl.baiduy = ConvertBase64(items[1]); 56 } 57 } 58 } 59 } 60 } catch (Exception e) { 61 bl.ok = false; 62 } 63 return bl.ok; 64 } 65 private static float ConvertBase64(String str) { 66 byte[] bs = Base64.decode(str); 67 return Float.valueOf(new String(bs)); 68 }
经纬度转换接口http://map.yanue.net/gps.html
牛人主页:http://map.yanue.net/
时间: 2024-10-04 02:57:30