首先得到百度地图创建自己的应用:
百度地图: 官网
我选用的是服务端:
复杂自己的AK,下面的代码会用到。
测试类:
/**
* @author yu
* @ClassName BaiduAPI.java
* @Description 百度API接口-地址转经纬度
* @createTime 2021-08-30 14:40
**/
@SpringBootTest
public class BaiduAPI {
@Autowired
private CorpMapper CorpMapper;
public static Map<String, Double> getLatAndLngByAddress(String addr){
String address = "";
String lat = "";
String lng = "";
try {
address = java.net.URLEncoder.encode(addr,"UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String url = "https://api.map.baidu.com/geocoding/v3/?address="+address+
"&output=json&ak=自己的AK&callback=showLocation ";
URL myURL = null;
URLConnection httpsConn = null;
//进行转码
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
}
try {
httpsConn = (URLConnection) myURL.openConnection();
if (httpsConn != null) {
InputStreamReader insr = new InputStreamReader(
httpsConn.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(insr);
String data = null;
if ((data = br.readLine()) != null) {
lat = data.substring(data.indexOf("\"lat\":")
+ ("\"lat\":").length(), data.indexOf("},\"precise\""));
lng = data.substring(data.indexOf("\"lng\":")
+ ("\"lng\":").length(), data.indexOf(",\"lat\""));
}
insr.close();
}
} catch (IOException e) {
}
Map<String, Double> map = new HashMap<String, Double>();
map.put("lat", new Double(lat));
map.put("lng", new Double(lng));
return map;
}
@Test
public void adressToLngLat(){
for (int i = 9;i<=CorpMapper.getSum();i++) {
Corp coInfo = CorpMapper.selectById(i);
if (coInfo.getAddr().equals(null) || coInfo.getAddr().equals("")) {
CorpMapper.updateById(new Corp((long) i, 0.00,0.00));
}else {
Map<String, Double> map = new HashMap();
map = getLatAndLngByAddress(coInfo.getAddr());
Corp Corp = new Corp();
CorpMapper.updateById(new Corp((long) i, map.get("lng"), map.get("lat")));
}
}
}
}
dao
public interface CorpMapper extends BaseMapper<Corp> {
@Select("select count(*) from corp")
int getSum();
}
偷懒用到了mybatis-plus
实体类等和数据库对应就行。