通过ip得到所在城市,以及城市所在经纬度坐标(监控系统中用的该代码,小航哥)
监控系统中就是利用的该段代码,实现通过ip得到所在城市,以及城市所在经纬度坐标,最后得以利用echarts实现模拟迁移的效果
api官方介绍: http://lbsyun.baidu.com/index.php?title=webapi/ip-api
package org.logMonitor.utils; import net.sf.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.nio.charset.Charset; /** * Created by lenovo on 2018/1/21. * 通过ip得到所在城市,以及城市所在经纬度坐标 */ public class AddressUtilsBaidu { public static String getAddrName(String ip) { try{ //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=iTrwV0ddxeFT6QUziPQh2wgGofxmWkmg&ip="+ip+"&coor=bd09ll"); /* 获取到的json对象: * {"address":"CN|河北|保定|None|UNICOM|0|0", * "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307}, * "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}}, * "status":0} */ JSONObject content=json.getJSONObject("content"); //获取json对象里的content对象 JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail String city=addr_detail.get("city").toString(); //获取市名,可以根据具体需求更改,如果需要获取省份的名字,可以把“city”改成“province”... JSONObject point=content.getJSONObject("point");//从content对象里获取point经纬度 String x=point.get("x").toString();//从point对象里获取x经度 String y=point.get("y").toString();//从point对象里获取y纬度 return city+"经度"+x+"纬度"+y; }catch (Exception e){ return "内网IP"; } } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = null; try { is = new URL(url).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { //关闭输入流 is.close(); } } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static void main(String[] args) throws IOException, JSONException { //System.out.println(getAddrName("192.168.2.112")); System.out.println(getAddrName("122.49.20.247")); } }
,