A detailed tutorial on using Baidu Maps

1. Baidu map introduction

  1. Baidu map APIIt is a set of Baidu map-basedAPI, including JavaScript, iOS, Andriod, static maps, Web services and other versions, providing basic
    maps, location search, surrounding search, bus driving navigation, location services, geocoding and other functions.

  2. The official website of Baidu Maps API is Baidu Maps

  3. Before using it, you need to register as a developer, follow the prompts for real-name authentication, and the registration is successful.
    insert image description here

  4. After the registration is successful, open the console, enter the application management, enter the application name, type, white listWrite English half-width *
    insert image description here

  5. The creation is successful, the following figure is displayed, and the key AK will be displayedinsert image description here

2. The use of Baidu map

1. Steps to use Baidu Map

  1. Get the key AK of the application just created, import the js of Baidu map, and replace your own AK with your own key AK, as shown in the figure below
    <script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=你自己的AK"></script>
    insert image description here
  2. Create a map container
    <div id="container"></div>
  3. Initialize the map
    var map=new BMap.Map("container")
  4. Create a map center point
    var point new BMap.point(经度,纬度)
  5. Set the center point and scroll wheel to zoom
    map.centerAndzoom(point, 1 5); ​//鼠标滚轮缩放 map.enableScrollWheelZoom(true);
    After the above steps, a map is created

2. Add controls

After creating a map, add scale control, zoom control, city list control

var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
map.addControl(scaleCtrl);
var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
map.addControl(zoomCtrl);
var cityCtrl = new BMapGL.CityListControl();  // 添加城市列表控件
map.addControl(cityCtrl);

insert image description here

3. Draw content on the map (overlay)

All content that is superimposed or overlaid on the map is collectively referred to as a map overlay.

  1. plot points on the map
var  p = new BMapGL.Point(e.latlng.lng,e.latlng.lat);
// 创建标记
var  m = new BMapGL.Marker(p);
  1. Draw polylines on the map
var polyline = new BMapGL.Polyline(line,{
    
    strokeStyle:"dashed",strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
  1. draw polygons on the map
var polygone = new BMapGL.Polygon(line,{
    
    fillColor:"red",strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5})
  1. Draw a circle on the map
  // 绘制圆圈	
var circle = new BMapGL.Circle(point,2000,{
    
    strokeColor:"green"});
// 添加圆圈
map.addOverlay(circle);
  1. add callout
var label = new BMapGL.Label("中国前端学习基地", {
    
           // 创建文本标注
        position: point,                          // 设置标注的地理位置
        offset: new BMapGL.Size(0, 0)           // 设置标注的偏移量

})  
// 添加标签
map.addOverlay(label);                        // 将标注添加到地图中
// 设置标签的样式
label.setStyle({
    
    
        fontSize:"32px",
        color:"red"

})
  1. Add info window
var opts = {
    
    
    width: 250,     // 信息窗口宽度
    height: 100,    // 信息窗口高度
    title: "Hello"  // 信息窗口标题
}
var infoWindow = new BMapGL.InfoWindow("World", opts);  // 创建信息窗口对象
map.openInfoWindow(infoWindow, map.getCenter());        // 打开信息窗口
  1. remove covering
    map.removeOverlay(覆盖物);

4. Map events

  1. markers.addEventListenerEvents can be added to map overlays.
    The addEventListener method has two parameters: the name of the event to listen to and the function to call when the event is triggered.
  2. passremoveEventListenerMethod to remove the listener for the event
map.addEventListener('click', handleClick);
function handleClick (e) {
    
    
    alert('点击的经纬度:' + e.latlng.lng + ', ' + e.latlng.lat);
    var mercator = map.lnglatToMercator(e.latlng.lng, e.latlng.lat);
    alert('点的墨卡托坐标:' + mercator[0] + ', ' + mercator[1]);
}
map.removeEventListener('click', handleClick);

5. Search function of Baidu map

1. passlocal.searchsearch for the keyword

var local = new BMapGL.LocalSearch(map, {
    
    
                         renderOptions: {
    
    
                                        map: map
                                }
                        })

6. How to use Baidu map in Vue project

method one

  1. public/index.html script introduces Baidu map

  2. Define data in the component
    map: null, point: null, marker: null, keyword: "", local: null,

  3. mounted initialization project

// 初始化地图
        
                
                        this.map = new window.BMapGL.Map(this.$refs.map);
                        // 准备一个中心点(经度,纬度)
                        this.point = new window.BMapGL.Point(116.404, 39.915);
                        // 设置中心点和缩放级别
                        this.map.centerAndZoom(this.point, 15);
                        // 鼠标滚轮缩放
                        this.map.enableScrollWheelZoom(true);
                        //添加一个点
                        this.marker = new window.BMapGL.Marker(this.point);
                        //添加覆盖物
                        this.map.addOverlay(this.marker);
                        // 百度地图API功能
                        this.local = new window.BMapGL.LocalSearch(this.map, {
    
    
                                renderOptions: {
    
    
                                        map: this.map

                                }

                        });

                },
  1. Monitor data changes and update the map
watch: {
    
    
        
                
                        keyword:{
    
    
                                handler() {
    
    
                                        if (this.keyword === "") {
    
    
                                                this.local.clearResults()
                                                this.map.centerAndZoom(this.point, 15);

                                        } else {
    
    
                                                this.local.search(this.keyword)

                                        }

                                }

                        }

                }

Method Two

  1. You can use the vue map plugin, vue-baidu-map 170-Vue2-based Baidu map component library. The official website is dafork

3. The case of Baidu Maps

  1. Basic map example
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#container{
     
     
				width: 800px;
				height: 600px;
			}
		</style>
		<!-- 01 导入js -->
		<script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=KHp5uI3NGByiMP20lWf2dEMCWUbYuS6c"></script>
	</head>
	<body>
		<!-- 准备容器 -->
		<div id="container"></div>
		<script>
			// 初始化地图
			var map = new BMapGL.Map("container")
			// 准备一个中心点(经度,纬度)
			var point = new BMapGL.Point(116.404, 39.915);
			// 设置中心点和缩放级别
			map.centerAndZoom(point, 15); 
			// 鼠标滚轮缩放
			map.enableScrollWheelZoom(true);
			
			// 不要去记忆,要去官网粘贴复制
		</script>
	</body>
</html>

insert image description here

  1. Map control case
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#container{
     
     
				width: 800px;
				height: 600px;
			}
		</style>
		<!-- 01 导入js -->
		<script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=g2DVs4pVwq1DDviUCkXgMDK9ujPx9d5B"></script>
	</head>
	<body>
		<!-- 准备容器 -->
		<div id="container"></div>
		<script>
			// 初始化地图
			var map = new BMapGL.Map("container")
			// 准备一个中心点(经度,纬度)
			var point = new BMapGL.Point(116.404, 39.915);
			// 设置中心点和缩放级别
			map.centerAndZoom(point, 15); 
			// 鼠标滚轮缩放
			map.enableScrollWheelZoom(true);
			
			// 不要去记忆,要去官网粘贴复制
			var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
			map.addControl(scaleCtrl);
			var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
			map.addControl(zoomCtrl);
			var cityCtrl = new BMapGL.CityListControl();  // 添加城市列表控件
			map.addControl(cityCtrl);
		</script>
	</body>
</html>

insert image description here
3. Add point case

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#container{
     
     
				width: 800px;
				height: 600px;
			}
		</style>
		<!-- 01 导入js -->
		<script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=g2DVs4pVwq1DDviUCkXgMDK9ujPx9d5B"></script>
	</head>
	<body>
		<!-- 准备容器 -->
		<div id="container"></div>
		<script>
			// 初始化地图
			var map = new BMapGL.Map("container")
			// 准备一个中心点(经度,纬度)
			var point = new BMapGL.Point(113.665,34.784);
			// 设置中心点和缩放级别
			map.centerAndZoom(point, 15); 
			// 鼠标滚轮缩放
			map.enableScrollWheelZoom(true);
			
			// 添加一个点
			var marker =new BMapGL.Marker(point);
			// 添加覆盖物
			map.addOverlay(marker); 
			// 存储多个点
			var line = [];
			// 存储标记
			var markers = [];
			// 监听事件
			map.addEventListener("click",e=>{
     
     
				// 创建点
				var  p = new BMapGL.Point(e.latlng.lng,e.latlng.lat);
				// 创建标记
				var  m = new BMapGL.Marker(p);
				markers.push(m);
				// 添加标记
				map.addOverlay(m);
				// 存储点
				line.push(p);
			})
			map.addEventListener("dblclick",e=>{
     
     
				// 把第0个点放入到最后面
				line.push(line[0]);
				// 创建多边形先
				var polygone = new BMapGL.Polygon(line,{
     
     fillColor:"red",strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5})
				// var polyline = new BMapGL.Polyline(line,{strokeStyle:"dashed",strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
				// 添加线
				// map.addOverlay(polyline);
				 map.addOverlay(polygone);
				// 清空点的列表
				line = [];
				// stroke线,Color颜色,Weight粗细,OPacity透明度
				// 清空点
				markers.forEach(item=>map.removeOverlay(item));
				// 清空点
				markers = [];

			})
			
			var circle = new BMapGL.Circle(point,2000,{
     
     strokeColor:"green"});
			map.addOverlay(circle);
			
			 
		</script>
	</body>
</html>

insert image description here

  1. Add a marked case
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#container{
     
     
				width: 800px;
				height: 600px;
			}
		</style>
		<!-- 01 导入js -->
		<script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=g2DVs4pVwq1DDviUCkXgMDK9ujPx9d5B"></script>
	</head>
	<body>
		<!-- 准备容器 -->
		<div id="container"></div>
		<script>
			// 初始化地图
			var map = new BMapGL.Map("container")
			// 准备一个中心点(经度,纬度)
			var point = new BMapGL.Point(113.665,34.784);
			// 设置中心点和缩放级别
			map.centerAndZoom(point, 15); 
			// 鼠标滚轮缩放
			map.enableScrollWheelZoom(true);
			
			// 添加一个点
			var marker =new BMapGL.Marker(point);
			// 添加覆盖物
			map.addOverlay(marker); 
			// 创建标签
			var label = new BMapGL.Label("中国前端学习基地", {
     
            // 创建文本标注
				position: point,                          // 设置标注的地理位置
				offset: new BMapGL.Size(0, 0)           // 设置标注的偏移量
			})  
			// 添加标签
			map.addOverlay(label);                        // 将标注添加到地图中
			// 设置标签的样式
			label.setStyle({
     
     
				fontSize:"32px",
				color:"red"
			})
			
			 
		</script>
	</body>
</html>

insert image description here

  1. Information window case
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#container{
     
     
				width: 800px;
				height: 600px;
			}
		</style>
		<!-- 01 导入js -->
		<script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=g2DVs4pVwq1DDviUCkXgMDK9ujPx9d5B&output=jsonp"></script>
	</head>
	<body>
		<!-- 准备容器 -->
		<div id="container"></div>
		<script>
			// 初始化地图
			var map = new BMapGL.Map("container")
			// 准备一个中心点(经度,纬度)
			var point = new BMapGL.Point(113.665,34.784);
			// 设置中心点和缩放级别
			map.centerAndZoom(point, 15); 
			// 鼠标滚轮缩放
			map.enableScrollWheelZoom(true);
			
			// 添加一个点
			var marker =new BMapGL.Marker(point);
			// 添加覆盖物
			map.addOverlay(marker); 
			
			var opts = {
     
     
			    width: 250,     // 信息窗口宽度
			    height: 200,    // 信息窗口高度
			    title: "学好前端,月薪过万"  // 信息窗口标题
			}
			// 信息窗口
			var infoWindow = new BMapGL.InfoWindow(`<p>前端很简单只有<strong>js</strong></p><img src="https://gimg3.baidu.com/search/src=http%3A%2F%2Fpics6.baidu.com%2Ffeed%2F37d12f2eb9389b50d7a9ec85016fcad6e6116e7c.jpeg%40f_auto%3Ftoken%3Db6954495aabfec6648f5a7b29905e75e&refer=http%3A%2F%2Fwww.baidu.com&app=2021&size=f360,240&n=0&g=0n&q=75&fmt=auto?sec=1667322000&t=622767397570980eb03b5acecd03756a" width="200">`, opts);  
			// 创建信息窗口对象
			map.openInfoWindow(infoWindow,point);        // 打开信息窗口
			//  map.getCenter() 获取到地图的中心位置
			
			marker.addEventListener("click",e=>{
     
     
				// 单击显示
				map.openInfoWindow(infoWindow,point);    
			})
			
			 
		</script>
	</body>
</html>

insert image description here

  1. Add search function
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#container{
     
     
				width: 800px;
				height: 600px;
			}
		</style>
		<!-- 01 导入js -->
		<script src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=g2DVs4pVwq1DDviUCkXgMDK9ujPx9d5B&output=jsonp"></script>
	</head>
	<body>
		<input type=""  value="" onchange="search(this)" />
		<!-- 准备容器 -->
		<div id="container"></div>
		<script>
			// 初始化地图
			var map = new BMapGL.Map("container")
			// 准备一个中心点(经度,纬度)
			var point = new BMapGL.Point(113.665,34.784);
			// 设置中心点和缩放级别
			map.centerAndZoom(point, 15); 
			// 鼠标滚轮缩放
			map.enableScrollWheelZoom(true);
			
			// 添加一个点
			var marker =new BMapGL.Marker(point);
			// 添加覆盖物
			map.addOverlay(marker); 
			// 创建一个本地搜索
			var local = new BMapGL.LocalSearch(map, {
     
     
					renderOptions:{
     
     map: map}
				});
			function search(e){
     
     
				// 表单值发生变化时候进行搜索
				local.search(e.value);
			}
			 
			
			 
		</script>
	</body>
</html>

insert image description here
The above are the knowledge points about Baidu Maps. If you don’t accumulate steps, you can reach thousands of miles. If you can read this blog patiently, it means that you are a person with potential. If you want to know more, it is recommended to read more official documents.insert image description here

Guess you like

Origin blog.csdn.net/m0_55734030/article/details/127620824