百度地图API使用 (JS案例 Web服务器案例)

前言

这几天在项目中用到了百度地图这个插件,所以准备花点时间记录一下心得,好东西就要分享出来!

1. 百度地图使用方式

1.1 操作流程

在这里插入图片描述

1.2 申请AK密钥

如果想调用百度地图API,需要先获取一个百度地图API的AK密钥
百度地图API官方文档: https://lbsyun.baidu.com/

在这里插入图片描述

我的需求时web端,所有这里选择了浏览器端。
白名单 上线前使用*号,线上正式ak请设置合理的IP白名单

在这里插入图片描述

2. 技术使用

主要学习: 定位技术、路径规划和导航

2.1 打开JavaScript API

在这里插入图片描述

2.2 点击开发指南中的Hello World

在这里插入图片描述

2.3 完成地图展示

至此,我们就快速创建了一张以天安门为中心的地图~
注意: ak=必须时自己申请的

<!DOCTYPE html>
<html>
	<head>
	    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	    <title>Hello, World</title>
	    <style type="text/css">
	        html{
	        	height:100%
	        }
	        body{
	        	height:100%;
	        	margin:0px;
	        	padding:0px
	        }
	        #container{
	        	height:100%
	        }
	    </style>
	    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=iG0Qt0gY2IMtf99aZe0j7d1cNnXxIhwM"></script>
	</head>

	<body>
		<div id="container"></div>
		<script type="text/javascript">
		    // 创建地图实例
		    var map = new BMap.Map("container");
		    // 创建点坐标
		    var point = new BMap.Point(116.404, 39.915);
		    // 初始化地图,设置中心点坐标和地图级别
		    map.centerAndZoom(point, 15);
		</script>
	</body>
</html>

3. 常见API

相关API 可以在这里查找 这里只介绍一些常用的

在这里插入图片描述

3.1 开启地图缩放功能

	map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

3.2 添加标注

可以给地图中的点添加标注,添加标注的时候要一个point(坐标)对象,把标注添加到坐标位置。

	var marker = new BMap.Marker(point);        // 创建标注    
	map.addOverlay(marker);     

3.3 标注添加点击事件

	marker.addEventListener("click", function(){    
	    alert("您点击了标注");    
	}); 

3.4 推拽标注点

	marker.enableDragging();    
	marker.addEventListener("dragend", function(e){    
	    alert("当前位置:" + e.point.lng + ", " + e.point.lat);    
	}) 

3.5 信息窗口

	var opts = {    
	    width : 250,     // 信息窗口宽度    
	    height: 100,     // 信息窗口高度    
	    title : "Hello"  // 信息窗口标题   
	}    
	var infoWindow = new BMap.InfoWindow("World", opts);  // 创建信息    
	map.openInfoWindow(infoWindow, map.getCenter());      // 打开信息

4. 案例-JS

4.1 百度坐标

展示地图,当点击地图上的一点时,显示点图标并且弹出当前点的坐标.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hello, World</title>
    <style type="text/css">
        html{height:100%}
        body{height:100%;margin:0px;padding:0px}
        #container{height:100%}
    </style>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=iG0Qt0gY2IMtf99aZe0j7d1cNnXxIhwM">
    </script>
</head>

<body>
	<div id="container"></div>
	<script type="text/javascript">
	    // 展示地图
	    var map = new BMap.Map("container");
	    var point = new BMap.Point(116.404, 39.915);
	    map.centerAndZoom(point, 15);
	    map.enableScrollWheelZoom(true);
	
	
	
	    //添加地图单击事件
	    map.addEventListener("click", function(e){
	        // 获取经纬度
	        point= new BMap.Point(e.point.lng,e.point.lat)
	        // 创建标记点
	        let marker = new BMap.Marker(point);
	        // 删除标记点
	        map.clearOverlays();
	        // 添加标记点
	        map.addOverlay(marker);
	
	        // 提示层
	        var opts = {
	            width : 250,     // 信息窗口宽度
	            height: 100,     // 信息窗口高度
	            title : "定位信息"  // 信息窗口标题
	        };
	        // 展示信息
	        let info = "当前位置:" + e.point.lng + ", " + e.point.lat;
	        // 创建信息窗口对象
	        var infoWindow = new BMap.InfoWindow(info, opts);
	        // 打开信息窗口
	        map.openInfoWindow(infoWindow, point);
	    })
	</script>
</body>
</html>

在这里插入图片描述

4.2 公司地址

实现地图展示公司位置,并展示提示框介绍

<!DOCTYPE html>
<html>
	<head>
	    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	    <title>Hello, World</title>
	    <style type="text/css">
	        html{height:100%}
	        body{height:100%;margin:0px;padding:0px}
	        #container{height:100%}
	    </style>
	    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=iG0Qt0gY2IMtf99aZe0j7d1cNnXxIhwM">
	    </script>
	</head>
	
	<body>
		<div id="container"></div>
		<script type="text/javascript">
		    //114.51189910433335, 36.58220995988854
		
		    // 展示地图
		    var map = new BMap.Map("container");
		    var point = new BMap.Point(114.51189910433335, 36.58220995988854);
		    map.centerAndZoom(point, 18);
		    map.enableScrollWheelZoom(true);
		
		    //禁止推拽
		    map.disableDragging();
		    // 创建标记点
		    let marker = new BMap.Marker(point);
		    // 添加标记点
		    map.addOverlay(marker);
		    // 提示层
		    var opts = {
		        width : 250,     // 信息窗口宽度
		        height: 100,     // 信息窗口高度
		        title : "定位信息"  // 信息窗口标题
		    };
		    // 展示信息
		    let info = "当前位置:";
		    // 创建信息窗口对象
		    var infoWindow = new BMap.InfoWindow(info, opts);
		    // 打开信息窗口
		    map.openInfoWindow(infoWindow, point);
		</script>
	</body>
</html>

在这里插入图片描述

4.3 路线规划

实现从地图选择的点到鹏泰大厦路径

<!DOCTYPE html>
<html>
	<head>
	    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	    <title>Hello, World</title>
	    <style type="text/css">
	        html{height:100%}
	        body{height:100%;margin:0px;padding:0px}
	        #container{height:100%}
	    </style>
	    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=iG0Qt0gY2IMtf99aZe0j7d1cNnXxIhwM">
	    </script>
	</head>
	
	<body>
		<div id="container"></div>
		<div id='result'>根据起点和终点经纬度驾车导航路线</div>
		<script type="text/javascript">
		    //114.51189910433335, 36.58220995988854
		
		    // 展示地图
		    var map = new BMap.Map("container");
		    var point = new BMap.Point(114.51189910433335, 36.58220995988854);
		    map.centerAndZoom(point, 18);
		    map.enableScrollWheelZoom(true);
		    //添加标记点
		    var marker = new BMap.Marker(point);        // 创建标注
		    map.addOverlay(marker);
		
		    //地图单击事件
		    map.addEventListener("click",function(e){
		        //清除离线
		        map.clearOverlays();
		        //获取点击时的经纬度
		        let p2 = new BMap.Point( e.point.lng,e.point.lat);
		
		        //计算距离
		        var output = "从当前位置到点击的位置驾车需要";
		        var searchComplete = function (results){
		            if (transit.getStatus() != BMAP_STATUS_SUCCESS){
		                return ;
		            }
		            var plan = results.getPlan(0);
		            //获取分钟数
		            output += plan.getDuration(true) + "\n";                //获取时间
		            //获取总距离
		            output += "总路程为:" ;
		            output += plan.getDistance(true) + "\n";             //获取距离
		        }
		        //创建路线
		        var transit = new BMap.DrivingRoute(map, {
		            renderOptions: {map: map},
		            onSearchComplete: searchComplete,
		            onPolylinesSet: function(){
		                setTimeout(function(){alert(output)},"500");
		            }});
		        //生成驾驶路线
		        transit.search(p2, point);
		    })
		</script>
	</body>
</html>

在这里插入图片描述

5. 案例-WEB服务

5.1 IP定位

得到用户请求的IP并返回用户所在的地址.

5.1.1 Controller
@RestController
public class MapController {

    private final String ak = "iG0Qt0gY2IMtf99aZe0j7d1cNnXxIhwM";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getAddress")
    public Object getAddressUseIP(HttpServletRequest request) throws URISyntaxException {
        //获取本地IP地址
        String ip = request.getRemoteHost();
        ip="106.115.32.5";
        String url = "http://api.map.baidu.com/location/ip?ak="+ak+"&ip="+ip+"&coor=bd09ll";

        //想百度地图发起请求
        ResponseEntity<Map> forEntity = restTemplate.getForEntity(new URI(url), Map.class);
        Map body = forEntity.getBody();
        return  body;
    }
}
5.1.2 主运行入口
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

}
5.1.3 显示图

在这里插入图片描述

5.1.4 文档位置

在这里插入图片描述

5.2 天气查询

5.2.1 Controller
private final String ak = "iG0Qt0gY2IMtf99aZe0j7d1cNnXxIhwM";

@GetMapping("/getWeather")
   public Object getWeather(String code) throws URISyntaxException {
       //获取本地IP地址
       String url = "http://api.map.baidu.com/weather/v1/?district_id="+code+"&data_type=all&ak="+ak1+"";
       //想百度地图发起请求
       ResponseEntity<String> forEntity = restTemplate.getForEntity(new URI(url), String.class);
       return  forEntity;
   }
5.2.2 主运行入口
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

}
5.2.3 效果图

在这里插入图片描述

5.2.4 文档位置

在这里插入图片描述

5.3 鹰眼轨迹服务

5.3.1 获取鹰眼服务ID(Serivce ID)

在这里插入图片描述
在这里插入图片描述

5.3.2 创建围栏
	@PostMapping("/createFace")
    public String createFace() throws URISyntaxException {
        String url = "http://yingyan.baidu.com/api/v3/fence/createcirclefence";
        LinkedMultiValueMap map = new LinkedMultiValueMap();
        map.add("ak",ak1);
        map.add("service_id",228519);
        map.add("longitude",114.51189910433335);
        map.add("latitude",36.5822099598885);
        map.add("radius",5000);
        map.add("coord_type","bd09ll");
        ResponseEntity<String> forEntity = restTemplate.postForEntity(new URI(url),map, String.class);
        return forEntity.getBody();
    }

在这里插入图片描述

5.3.3 查询围栏
	 @GetMapping("/queryFace")
	 public String queryFace(String ids) throws URISyntaxException {
	      String url = "http://yingyan.baidu.com/api/v3/fence/list";
	      url+="?ak="+ak1;
	      url+="&service_id="+228519;
	      url+="&fence_ids="+ids;
	      ResponseEntity<String> forEntity = restTemplate.getForEntity(new URI(url),String.class);
	      return forEntity.getBody();
	  }

在这里插入图片描述

5.3.4 删除围栏
	@PostMapping("/deleteFace")
    public String deleteFace(String ids) throws URISyntaxException {
        String url="http://yingyan.baidu.com/api/v3/fence/delete";
        LinkedMultiValueMap map = new LinkedMultiValueMap();
        map.add("ak",ak1);
        map.add("service_id",228519);
        map.add("fence_ids",ids);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(new URI(url), map,String.class);
        return forEntity.getBody();
    }

在这里插入图片描述

5.3.5 创建终端
    @PostMapping("/createEntity")
    public String createEntity(String name) throws URISyntaxException {
        String url = "http://yingyan.baidu.com/api/v3/entity/add";
        LinkedMultiValueMap map = new LinkedMultiValueMap();
        map.add("ak",ak1);
        map.add("service_id",228519);
        map.add("entity_name",name);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(new URI(url), map,String.class);
        return forEntity.getBody();
    }

在这里插入图片描述

5.3.6 终端绑定围栏
	@PostMapping("/addFenceEntity")
    public String  addFenceEntity(int fence,String name) throws URISyntaxException {
        String url = "http://yingyan.baidu.com/api/v3/fence/addmonitoredperson";
        LinkedMultiValueMap map = new LinkedMultiValueMap();
        map.add("ak",ak1);
        map.add("service_id",228519);
        map.add("fence_id",fence);
        map.add("monitored_person",name);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(new URI(url), map,String.class);
        return forEntity.getBody();
    }

在这里插入图片描述

5.3.7 轨迹上传
@PostMapping("/addPoint")
    public String  addPoint(String name,double latitude,double longitude) throws URISyntaxException {
        String url = "http://yingyan.baidu.com/api/v3/track/addpoint";
        LinkedMultiValueMap map = new LinkedMultiValueMap();
        map.add("ak",ak1);
        map.add("service_id",228519);
        map.add("entity_name",name);
        map.add("latitude",latitude);
        map.add("longitude",longitude);
        map.add("loc_time",(long)(new Date().getTime()/1000));
        map.add("coord_type_input","bd09ll");
        ResponseEntity<String> forEntity = restTemplate.postForEntity(new URI(url), map,String.class);
        return forEntity.getBody();
    }

在这里插入图片描述
在这里插入图片描述

5.3.8 查询是否在范围内
	@GetMapping("/queryStatus")
    public String queryStatus(String name) throws URISyntaxException {
        String url = "http://yingyan.baidu.com/api/v3/fence/querystatus";
        url+="?ak="+ak1;
        url+="&service_id="+228519;
        url+="&monitored_person="+name;
        ResponseEntity<String> forEntity = restTemplate.getForEntity(new URI(url),String.class);
        return forEntity.getBody();
    }

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自学之路←_←

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值