Home >Web Front-end >JS Tutorial >How to use JS and Baidu Maps to add custom location markers to the map
How to use JS and Baidu Map to implement the function of adding custom location markers to the map
Introduction: Baidu Map is a very commonly used map service, which provides a wealth of Map presentation and interactive features, including adding custom place markers. Using JS and Baidu Map API, we can easily implement the function of adding custom location markers on the map. The following is a specific code example:
Step 1: Preparation
First, import the Baidu Map API file in your HTML file, as shown below:
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的百度地图API密钥"></script>
Create a div element of the map container in the page, specify the width and height, As shown below:
<div id="map" style="width:800px;height:600px;"></div>
Add a button or other event-triggering element to trigger the function of adding location markers, as shown below:
<button id="addMarkerBtn">添加标记</button>
Step 2: Add map and marker functions
Initialize the map object in JS as follows:
var map = new BMap.Map("map"); // 创建地图实例 var point = new BMap.Point(116.404, 39.915); // 创建一个初始坐标点 map.centerAndZoom(point, 15); // 初始化地图,设置中心点和缩放级别 map.addControl(new BMap.NavigationControl()); // 添加平移缩放控件 map.addControl(new BMap.ScaleControl()); // 添加比例尺控件
Add map click Event, used to add location markers by clicking on the map, as shown below:
map.addEventListener("click", function(e) { var point = e.point; // 获取点击的坐标点 var marker = new BMap.Marker(point); // 创建新的地点标记 map.addOverlay(marker); // 将标记添加到地图上 });
Add button click event, used to trigger map click event, as shown below:
var addMarkerBtn = document.getElementById("addMarkerBtn"); addMarkerBtn.addEventListener("click", function() { map.addEventListener("click", function(e) { var point = e.point; // 获取点击的坐标点 var marker = new BMap.Marker(point); // 创建新的地点标记 map.addOverlay(marker); // 将标记添加到地图上 }); });
Step 3: Test the effect
Save the above code and open the HTML file in the browser, you will see a map page with the function of adding custom location markers. Click anywhere on the map and a new location marker will appear on the map.
Note:
Summary:
Through the above steps, we can use JS and Baidu Map API to implement the function of adding custom location markers to the map. This is useful for websites or applications that need to mark specific locations. I hope the code examples in this article can help you!
The above is the detailed content of How to use JS and Baidu Maps to add custom location markers to the map. For more information, please follow other related articles on the PHP Chinese website!