search
HomeWeb Front-endHTML TutorialSimple use of Baidu map - add polylines, circles, etc. (html, js)_html/css_WEB-ITnose

Overview of map overlays

All content that is superimposed or covered on the map is collectively referred to as map overlays. Such as annotations, vector graphic elements (including polylines, polygons and circles), information windows, etc. Overlays have their own geographic coordinates, and when you drag or zoom the map, they move accordingly.

The map API provides the following types of overlays:

  • Overlay: The abstract base class of overlays. All overlays inherit the methods of this class.
  • Marker: Marker represents a point on the map, and the mark icon can be customized.
  • Label: Represents a text label on the map. You can customize the text content of the label.
  • Polyline: Represents a polyline on the map.
  • Polygon: Represents a polygon on the map. A polygon is similar to a closed polyline, but you can also add a fill color to it.
  • Circle: Represents a circle on the map.
  • InfoWindow: The information window is also a special overlay that can display richer text and multimedia information. Note: Only one information window can be open on the map at the same time.
  • You can use the map.addOverlay method to add an overlay to the map, and the map.removeOverlay method to remove the overlay. Note that this method does not apply to InfoWindow.

    One. Polyline

    Polyline represents the polyline overlay on the map. It consists of a set of points and connects these points to form a polyline.

    Add polyline

    Polyline is drawn as a series of straight segments on the map. The color, thickness, and transparency of these segments can be customized. The color can be a hexadecimal number (for example: #ff0000) or a color keyword (for example: red).

    Polyline drawing requires the browser to support the vector drawing function. In Internet Explorer, the map uses VML to draw polylines; in other browsers, use SVG or Canvas

    The following code snippet creates a 6-pixel-wide blue polyline between two points:

    var polyline = new BMap.Polyline([       new BMap.Point(116.399, 39.910),       new BMap.Point(116.405, 39.920)     ],     {strokeColor:"blue", strokeWeight:6, strokeOpacity:0.5}    );    map.addOverlay(polyline);

    Two. Custom overlay

    API supports user-defined overlays since version 1.1.

    To create a custom overlay , you need to do the following:

     1. Define a constructor of the custom overlay, and pass some constructor parameters Free variables.

    2. Set the prototype attribute of the custom overlay object to an instance of Overlay so that it can inherit the overlay base class.

     3. Implement the initialize method. When the map.addOverlay method is called, the API will call this method.

     4. Implement the draw method.

    Define the constructor and inherit Overlay

    First you need to define the constructor of the custom overlay, in the example below we define a constructor called SquareOverlay , which contains two parameters: center point and side length, and is used to create a square overlay on the map.

    // 定义自定义覆盖物的构造函数  function SquareOverlay(center, length, color){     this._center = center;     this._length = length;     this._color = color;    }    // 继承API的BMap.Overlay    SquareOverlay.prototype = new BMap.Overlay();

    Initialize the custom overlay

    When calling the map.addOverlay method When adding a custom overlay, the API will call the object's initialize method to initialize the overlay. During the initialization process, the DOM elements required for the overlay need to be created and added to the corresponding container of the map.

    The map provides several containers for overlay display. These container elements can be obtained through the map.getPanes method. They include:

  • floatPane
  • markerMouseTarget
  • floatShadow
  • labelPane
  • markerPane
  • mapPane
  • These objects represent different cover container elements, and there is an overlay relationship between them. The top layer It is a floatPane, used to display the content of the information window. The following is the annotation click area layer, the information window shadow layer, the text annotation layer, the annotation layer and the vector graphics layer.

    Our custom square cover can be added to any layer. Here we choose to add it to the markerPane as one of its child nodes.

    // 实现初始化方法  SquareOverlay.prototype.initialize = function(map){    // 保存map对象实例    this._map = map;         // 创建div元素,作为自定义覆盖物的容器    var div = document.createElement("div");     div.style.position = "absolute";         // 可以根据参数设置元素外观    div.style.width = this._length + "px";     div.style.height = this._length + "px";     div.style.background = this._color;      // 将div添加到覆盖物容器中    map.getPanes().markerPane.appendChild(div);      // 保存div实例    this._div = div;      // 需要将div元素作为方法的返回值,当调用该覆盖物的show、   // hide方法,或者对覆盖物进行移除时,API都将操作此元素。    return div;    }

    Drawing the overlay

    So far we have only added the overlay to the map, but not placed it in the right position. You need to set the position of the overlay in the draw method. Whenever the map state changes (for example, position movement, level change), the API will call the overlay's draw method to recalculate the position of the overlay. The map.pointToOverlayPixel method can be used to convert geographic coordinates to the required pixel coordinates of the overlay.

    // 实现绘制方法   SquareOverlay.prototype.draw = function(){    // 根据地理坐标转换为像素坐标,并设置给容器     var position = this._map.pointToOverlayPixel(this._center);     this._div.style.left = position.x - this._length / 2 + "px";     this._div.style.top = position.y - this._length / 2 + "px";    }

    Add Overlay

    You have now completed a complete Custom overlays can be written and added to the map.

    // 初始化地图  var map = new BMap.Map("container");    var point = new BMap.Point(116.404, 39.915);    map.centerAndZoom(point, 15);    // 添加自定义覆盖物   var mySquare = new SquareOverlay(map.getCenter(), 100, "red");    map.addOverlay(mySquare);

    Three. Add an ellipse

    <!DOCTYPE html><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />    <style type="text/css">        body, html {width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}        #allmap{width:100%;height:500px;}        p{margin-left:5px; font-size:14px;}    </style>    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>    <script type="text/javascript" src="http://api.map.baidu.com/library/CurveLine/1.5/src/CurveLine.min.js"></script>    <title>添加椭圆</title></head><body>    <div id="allmap"></div>    <p>在地图上添加一个椭圆,圆的颜色为蓝色、线宽6px、透明度为1,填充颜色为白色,透明度为0.5</p></body></html><script type="text/javascript">    // 百度地图API功能    var map = new BMap.Map("allmap");    var point = new BMap.Point(116.404, 39.915);    map.centerAndZoom(point, 10);        //centre:椭圆中心点,X:横向经度,Y:纵向纬度    function add_oval(centre,x,y)    {        var assemble=new Array();        var angle;        var dot;        var tangent=x/y;        for(i=0;i<36;i++)        {            angle = (2* Math.PI / 36) * i;            dot = new BMap.Point(centre.lng+Math.sin(angle)*y*tangent, centre.lat+Math.cos(angle)*y);            assemble.push(dot);        }        return assemble;    }    var oval = new BMap.Polygon(add_oval(point,0.1,0.3), {strokeColor:"blue", strokeWeight:6, strokeOpacity:0.5});    map.addOverlay(oval);</script>

    Effect:

    Thank you for reading !

    Basic knowledge can be found at: http://www.cnblogs.com/0201zcr/p/4687220.html Baidu Map Incident

    http://www.cnblogs.com/0201zcr/p /4680461.html Add tag

       http://www.cnblogs.com/0201zcr/p/4679444.html Add map service

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

    The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

    What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

    The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

    What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

    The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

    What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

    Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

    How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

    The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

    What is the viewport meta tag? Why is it important for responsive design?What is the viewport meta tag? Why is it important for responsive design?Mar 20, 2025 pm 05:56 PM

    The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

    How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

    This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

    What is the purpose of the <iframe> tag? What are the security considerations when using it?What is the purpose of the <iframe> tag? What are the security considerations when using it?Mar 20, 2025 pm 06:05 PM

    The article discusses the <iframe> tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft