我们在程序中经常有地图相关业务,今天做一个小总结
核心方法
public static Map<String, BigDecimal> getLatAndLngByAddress(String addr) {
String address = "";
try {
address = java.net.URLEncoder.encode(addr, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String url = String.format("http://api.map.baidu.com/place/v2/search?"
+ "ak=youKey=json&query=%s®ion=全国", address);
URL myURL = null;
URLConnection httpsConn = null;
//进行转码
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
}
StringBuffer sb = new StringBuffer();
try {
httpsConn = (URLConnection) myURL.openConnection();
if (httpsConn != null) {
InputStreamReader insr = new InputStreamReader(
httpsConn.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(insr);
String data = null;
while ((data = br.readLine()) != null) {
sb.append(data);
}
insr.close();
}
} catch (IOException e) {
}
Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
JSONObject resultJson = JSON.parseObject(sb.toString());
JSONArray jsonArray = (JSONArray) resultJson.get("results");
JSONObject results0Obj = (JSONObject) jsonArray.get(0);
JSONObject locationObj = (JSONObject) results0Obj.get("location");
//纬度
BigDecimal lat = (BigDecimal) locationObj.get("lat");
//经度
BigDecimal lng = (BigDecimal) locationObj.get("lng");
map.put("lat", lat);
map.put("lng", lng);
return map;
}
main启动一下看看结果:
public static void main(String[] args) {
Map<String, BigDecimal> resultMap = getLatAndLngByAddress("北京市昌平区金燕龙大厦");
System.out.println(resultMap.toString());
}
测试一下
当然可以扩展的,比如电商项目中的店铺信息或者配送是否在指定范围内,都可以继续拓展,灵活性很高。