基于百度地图实现定位服务
可以基于百度地图实现位置打卡等的常见业务操作
1.注册为开发者
1.找到首页
2.点击控制台
3.创建自己的应用
4.下面的测试仅仅是测试环境
5.创建完成
2.编写服务器端代码
1.目录
2.conifg下
@Configuration
public class OkHttpConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}
3.controller下
@RestController
public class GetController {
@Resource
private RestTemplate restTemplate;
@Value("${ak}")
private String ak;
@GetMapping("/get")
public Object getAddrByUserIP(HttpServletRequest request) throws URISyntaxException {
String url = "https://api.map.baidu.com/location/ip?ak="+ak+"&coor=bd09ll";
//发送请求
ResponseEntity<Map> forEntity = restTemplate.getForEntity(new URI(url), Map.class);
Map result = forEntity.getBody();
return result;
}
}
4.application.properties
ak=xxxxx #自己上面注册的
5.启动测试
3.编写前端代码
<html>
<head>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div align="center">
<button id="button" onclick="get()">定位</button>
<div id="address" style="border-style:solid;width:100px;height:30px"></div>
</div>
<script>
function get() {
var data = $.parseJSON($.ajax({
url: "get",//请求方式
dataType: "json", //返回json
async: false
}).responseText);
//获取位置
var address = eval(data).content.address;
let it = document.getElementById('address');
it.innerHTML = address;
}
</script>
</body>
</html>