此方法使用的是百度地图
注意:
1. 本次采用的是免费受限普通IP方式, 不够精准, 如有更精确需求可以 花钱 购买高级服务
2. 普通IP方式范围目前仅限定国内IP定位
3. 需要注册获取相关秘钥ak
不多说, 采用百度地图调用方式相对更加简单, 直接上代码
package com.example.demo.utils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
public class BDIPUtils {
private static Logger logger = LoggerFactory.getLogger(BDIPUtils.class);
private static final String HTTP = "http://api.map.baidu.com/location/ip";
private static final String HTTPS = "https://api.map.baidu.com/location/ip";
private static final String AK = "f6geaGQcxUCpRwcGVvSyU";
private static final String COOR = "bd09ll";
/*@Resource
private RestTemplate restTemplate;*/
private RestTemplate restTemplate = new RestTemplate();
public JSONObject getDate(String ip) {
String url = HTTPS+"?coor=bd09ll&ak="+AK+"&ip="+ip;
return restTemplate.getForObject(url, JSONObject.class);
}
public static void main(String[] args) {
String ip = "115.236.64.138"; // 访问IP
BDIPUtils bdipUtils = new BDIPUtils();
JSONObject jsonObject = bdipUtils.getDate(ip);
logger.info("result={}", jsonObject.toJSONString());
if (jsonObject != null) {
JSONObject json = jsonObject.getJSONObject("content");
logger.info("地址={}", json.get("address"));
JSONObject pointJSON = json.getJSONObject("point");
logger.info("经度={}; 纬度={}", pointJSON.get("x"), pointJSON.get("y"));
}
}
}
执行后输出结果:
result={"address":"CN|浙江|杭州|None|CHINANET|0|0","content":{"address":"浙江省杭州市","address_detail":{"city":"杭州市","city_code":179,"district":"","province":"浙江省","street":"","street_number":""},"point":{"x":"120.21937542","y":"30.25924446"}},"status":0}
地址=浙江省杭州市
经度=120.21937542; 纬度=30.25924446