How to use JS and Baidu Map to implement the map custom icon function
Overview:
Baidu Map is a widely used map service API that provides Rich functions, including positioning, search, navigation, etc. When using Baidu Maps, we often need to display customized icons on the map to display specific information. This article will teach you how to use JavaScript and Baidu Map API to implement the map custom icon function, and provide specific code examples.
Steps:
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=your_api_key"></script>
var map = new BMap.Map("map"); map.centerAndZoom(new BMap.Point(116.404, 39.915), 14); map.enableScrollWheelZoom(true);
This code creates a map container with the id "map" and sets the center point and zoom level of the map.
var icon = new BMap.Icon("icon.png", new BMap.Size(30, 30), { anchor: new BMap.Size(15, 30), imageOffset: new BMap.Size(0, 0) }); var marker = new BMap.Marker(new BMap.Point(116.404, 39.915), { icon: icon }); map.addOverlay(marker);
This code creates an icon named "icon.png" and sets the size and position of the icon. Then, create a Marker object and add the custom icon to the Marker object. Finally, add the Marker object to the map using the map's addOverlay() method.
marker.addEventListener("click", function() { alert("点击了自定义图标"); });
This code adds a "click" event listener to the custom icon. When the user clicks on the icon, a prompt box pops up.
地图自定义图标 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=your_api_key"></script>
The above code sample demonstrates how to use JS and Baidu Map API to implement the map custom icon function. First, introduce the Baidu map API in the HTML file, then use JavaScript to create a map instance and set the center point and zoom level of the map. Next, create a custom icon and add it to the map. Finally, add a click event listener for the custom icon.
Conclusion:
Using JavaScript and Baidu Map API can easily implement the map custom icon function. By adding custom icons, we can display various information on the map and enhance the interactivity and visualization of the map. I hope this article will be helpful to you, and I wish you can create better results when using Baidu Maps!
The above is the detailed content of How to use JS and Baidu Maps to implement map custom icon function. For more information, please follow other related articles on the PHP Chinese website!