jsapi GL

The basic composition of

  • Import links in advance using script, SRC as the addressAk key of https://api.map.baidu.com/api?v=1.0&type=webgl&ak= application
  • Create a box that inserts a map, such as div, with an ID
  • useNew bmapgl.map ('id name ') get the box, the use ofNew BMaoGL.Point(latitude, longitude) sets the coordinate PointAnd then use the coordinate pointsThe centerAndZoom method (latitude and longitude instances, coordinate levels) is placed in the boxCan be
  • The next step is to add configuration properties to the map instance
<script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=M0e3sGleXofV4Us4ySHqxLuZCQmn5Db2">/ / import the CDN
</script>
<body> 
<div id="container"></div>
</body> 
<script type="text/javascript">
var map = new BMapGL.Map("container");// Create a map instance
var point = new BMapGL.Point(116.404.39.915);// Create point coordinates
map.centerAndZoom(point, 15);// Initialize the map, set the center point coordinates and map level
</script> 
Copy the code

Configuration items on the prototype

  • Official documents:
  • Version 1.0
  • Version 2.0
  • Version 3.0
Create an instance
  • The Map (‘ container id)
var map = new BMapGL.Map("container");
Copy the code
The size of the
  • Size(length, width)
new BMapGL.Size(10.25);
Copy the code
controls
  • Control class name (control position – leave blank);
newBmapgl. control class name (control location - leave blank);Copy the code
Icon class
  • Icon(Picture address, viewable area size, configuration items)
  • This parameter is optional
    • anchorThe offset of an icon’s registration point relative to the upper left corner of the icon
    • imageOffsetThe offset of the image used by the icon relative to the visible area. This function is equivalent to the background-position property in the CSS
    • imageSizeThe size of the image used by the icon. This function is equivalent to background-size in CSS. Can be used to achieve hd effect of HD screen
 var myIcon = new BMapGL.Icon("Address".new BMapGL.Size(90.30), {  
            anchor: new BMapGL.Size(10.25),// The offset of the icon's registration point from the icon's upper-left corner
            imageOffset: new BMapGL.Size(0.0 ), // Set the image offset
        });
Copy the code
Label class
  • This class represents text annotations on a map.
  • Label(text, configuration item)
		var point = new BMapGL.Point(116.404.39.915);
        var lable = new BMapGL.Label('123123', {position: point,   // Set the location of the annotation, if used as the title, do not set
            offset:new BMapGL.Size(10, -50)// Text offset
        });
        label.setStyle({ // Set the label style
            color: '# 000'.fontSize: '30px'.border: '2px solid #1E90FF'
        })
        map.addOverlay(label);  // Insert text annotations into the map
Copy the code
Bounds class
  • This class represents a rectangular region of geographic coordinates.
  • Usage:Bounds(SW: Point class instance, ne: Point class instance)Creates a rectangular region containing the coordinates of all given points. Sw represents the southwest corner of the rectangle, and ne represents the northeast corner of the rectangle
 var bounds = new BMapGL.Bounds(
 new BMapGL.Point(pStart.lng, pEnd.lat),// Latitude and longitude in the southwest corner
 new BMapGL.Point(pEnd.lng, pStart.lat)// Latitude and longitude of the northeast corner
 );
Copy the code
3 d class
  • This class allows the map to switch between 2D and 3D
  • Usage:NavigationControl3D({Anchor: position,offset: offset})
  • Setting the location is not currently supported
        var D = new BMapGL.NavigationControl3D({
            anchor:BMAP_ANCHOR_TOP_RIGHT,
            offset: new BMapGL.Size(-1000, -10)
        })
        map.addControl(D);
Copy the code
Create point coordinates
  • Point(longitude, latitude)
  • Instance attributes: LNG longitude, LAT latitude
var point = new BMapGL.Point(116.404.39.915);
point.lng/ / 116.404
point.lat/ / 39.915
Copy the code

Configuration items on the instance

Initialize the map
  • CenterAndZoom (point coordinates, map level)
  • The smaller the map level, the larger the zoom
map.centerAndZoom(point, 15);
Copy the code
Mouse pulley control map zooming
  • enableScrollWheelZoom(true)
  • The default is false, false does not control scaling
map.enableScrollWheelZoom(true);
Copy the code
Set the map rotation Angle and tilt Angle
  • setHeading(num); Rotation Angle, rotation on the y axis
  • setTilt(90); The Angle of tilt, the X-axis tilt
map.setHeading(90);// Rotate the y axis 90 degrees
map.setTilt(90);// The X-axis is tilted 90 degrees
Copy the code
Change map mode
  • Usage:SetMapType (types)
    • The optional value of type
    • BMAP_EARTH_MAPThe earth model
map.setMapType(BMAP_EARTH_MAP);// Change to Earth mode
Copy the code
(Add/close) Traffic flow layer
  • setTrafficOn(); add
  • setTrafficOff(); Shut down
map.setTrafficOn();// Add the traffic flow layer
map.setTrafficOff(); // Remove the traffic layer
Copy the code

controls

  • Method of use
  • New bmapgl. control class name (control position - leave blank);Creating controls
  • Instance. AddControl;Add controls to the map
Controls the name of the class
  • Abstract base classControlAll controls inherit methods and properties of this class. This class allows you to implement custom controls
  • scaleScaleControlBy default, it is located in the lower left of the map, showing the scale of the map
  • The zoomZoomControlThe default location is at the bottom right of the map and controls map level zooming
  • positioningLocationControlBy default, it is located in the lower left of the map for obtaining location
  • City selection listCityListControlBy default, it is located in the upper left of the map for city selection positioning
  • copyrightCopyrightControlBy default, it is located in the lower left of the map to display copyright information
The control position
  • A control position is an object consisting of an Anchor representing that fixed location and an offset representing the offset
  • Both anchor and offset are optional and not mandatory

New bmapgl. control class name ({anchor: value,offset: new bmapgl. Size(150, 5)});

anchor
  • Attribute values
  • BMAP_ANCHOR_TOP_LEFTRepresents the control positioned in the upper left corner of the map
  • BMAP_ANCHOR_TOP_RIGHTIndicates that the control is positioned in the upper right corner of the map
  • BMAP_ANCHOR_BOTTOM_LEFTRepresents the control positioned in the lower left corner of the map
  • BMAP_ANCHOR_BOTTOM_RIGHTRepresents the control located in the lower right corner of the map
offset
  • Set the offset,The offset can be negative, and negative is the opposite direction
  • New bmapgl. Size(left offset, right offset);
        var zoomCtrl = new BMapGL.ZoomControl({
	        anchor:BMAP_ANCHOR_TOP_LEFT,// Set the control to the upper left corner of the map
            offset: new BMapGL.Size(-10.10)// Start from the top left corner and move 10 pixels to the right without moving up or down
        }); // Sets the zoom control instance
        map.addControl(zoomCtrl);// Add a zoom control
Copy the code

Personalized map

  • Custom map style, personalized map
  • Customize steps: New -> Edit -> Publish style
  • There are two ways to use itAre based onInstance. SetMapStyleV2 ({})
    • Method 1:Use syuleId,After publishing the style, copy the styleId, making sure that the styleId is the same as the ak used
    • Method 2:Using styleJsonClick Publish Style and copy json
Matters needing attention
  • The setMapStyleV2 method needs to be executed after map initialization (centerAndZoom) is complete;
  • Style updates do not change the style ID
  • ifThe style ID is removed from the console, but the JavaScript API keeps calling. It will beRender the map with the default style
   map.setMapStyleV2({/ / use styleId
       styleId: '7e3243cb5ac0306e22f3319ca51a5a8f'
   });
   map.setMapStyleV2({
       styleJson: [{/ / use styleJson
           "featureType": "land"."elementType": "geometry"."stylers": {
               "color": "#2d252cff"."visibility": "on"}}});Copy the code

mulch

Method of use
  • Initialize the overlay instanceNew BMAPgl. overlay type (latitude and longitude instance - required, Configuration item - optional);
  • Appends overlay instances to the mapMap.addoverlay (overlay instance);
  • Delete the instanceRemoveOverlay (overlay instance);
  • Listen for coverage events:AddEventListener (' event type ',function)
Cover type
  • Abstract base classOverlayAll coverings inherit this method
  • pointMarkerRepresents the point on the map, can be customized annotation icon
  • Broken linePolylineRepresents a broken line on a map
  • polygonPolygonRepresents polygons on a map
  • roundCircleRepresents a circle on a map
Configuration items for different coverings
  • Configuration items are included in the{}inside
Point Marker This parameter is optional
  • icon
  • The value is an Icon instance
  • Set the icon hasOne of two ways
    • inInitialize theMarker"Is set in the configuration items
    • useOverlay instance. SetIcon (Icon instance)Set up the
// Initialize the icon instance
     var myIcon = new BMapGL.Icon("Address".new BMapGL.Size(90.30), {
            anchor: new BMapGL.Size(10.25),// The offset of the icon's registration point from the icon's upper-left corner
            imageOffset: new BMapGL.Size(0.0 ), // Set the image offset
        });
        // Create a annotation object and add it to the map
        var marker = new BMapGL.Marker(point, {
            icon: myIcon
        });
        
        var lable = new BMapGL.Label('123123', {// Initialize an instance of lable
            offset:new BMapGL.Size(10, -50)}); marker.setLabel(lable);// Add a text title to the annotation
        map.addOverlay(marker);
Copy the code
Polyline coverings
  • A Polyline is a Polyline covering on a map that contains a set of points connected to form a Polyline
  • Set the line
var polyline = new BMapGL.Polyline([
		new BMapGL.Point(116.399.39.910),
		new BMapGL.Point(116.405.39.920),
		new BMapGL.Point(116.425.39.900)] and {strokeColor:"blue".strokeWeight:2.strokeOpacity:0.5});
map.addOverlay(polyline);
Copy the code
Polygonal covering
  • A Polygon is a Polygon overlay on a map that contains a set of points. The polygon connects the points end to end in sequence, forming a closed figure.
  • Set polygon
Configuration items
  • strokeColor Type a stringBorder color
  • fillColor Type a stringFill color. When the parameter is null, the polyline overlay has no fill effect.
  • strokeWeight Type the numberEdge width, in pixels
  • strokeOpacity Type the numberEdge transparency, ranging from 0 to 1
  • fillOpacity Type the numberFill transparency
  • strokeStyle Type a stringThe bounding style, solid or bounding
var polygon = new BMapGL.Polygon([
        new BMapGL.Point(116.387112.39.920977),
        new BMapGL.Point(116.385243.39.913063),
        new BMapGL.Point(116.394226.39.917988),
        new BMapGL.Point(116.401772.39.921364),
        new BMapGL.Point(116.41248.39.927893)] and {strokeColor:"blue".strokeWeight:2.strokeOpacity:0.5});
map.addOverlay(polygon);
Copy the code
Point with height
  • Method of useBmapgl.marker3d (Latitude and Longitude instance, height, configuration item)
Configuration items
  • size Type the numberDot size, default is 50
  • shape Type the numberPoint shape, 1 is circle, 2 is square, default is 1. You can also use the corresponding constants BMAP_SHAPE_CIRCLE and BMAP_SHAPE_RECT
  • fillColor Type a stringThe color of the dot in the format ‘# XXXXXX ‘, for example ‘#f00’
  • fillOpacity Type the numberPoint transparency, range 0-1, default 0.8
  • icon Type IconA texture map of point in the format of an Icon object created by Icon
    // Create a location point
    var point = new BMapGL.Point(116.404.39.915);
    // Create a point with height
    var marker3d = new BMapGL.Marker3D(point, 8000, {
        size: 50.shape: BMAP_SHAPE_CIRCLE,
        fillColor: '# 454399'.fillOpacity: 0.6.icon: Icon class instance// You can omit this item if there is no background image
    });
    // Add points to the map
    map.addOverlay(marker3d);
Copy the code
3 d prismatic
  • Usage:Bmapgl.prism (Array< Point >, high, configuration item)
Configuration items
  • topFillColor Type a stringTop fill color
  • topFillOpacity Type the numberTop fill color transparency. The value ranges from 0 to 1
  • sideFillColor Type a stringSide fill color
  • sideFillOpacity Type the numberSide fill color transparency, ranging from 0 to 1
  • enableMassClear The type BooleanClearOverlays whether this overlay is being cleared by calling map.clearOverlays, defaults to true
var prism = new BMapGL.Prism(path, 5000, {
    topFillColor: '#5679ea'.topFillOpacity: 0.5.sideFillColor: '#5679ea'.sideFillOpacity: 0.9
});
map.addOverlay(prism);// Add the instance to the map
Copy the code
Ground overlay (image, video, Canvas)
  • Bmapgl.groundoverlay (Bounds instance, configuration item)
Configuration items
  • type Type a string‘video’ | ‘canvas’, the default image
  • url Type a stringVideo url | custom canvas object
  • opacity Type the numberLayer opacity, default is 1, range 0-1
        // Create the scope of the superposition display Bounds
        var pStart = new BMapGL.Point(116.447717.39.919173);
        var pEnd = new BMapGL.Point(116.453125.39.923475);
        var bounds = new BMapGL.Bounds(new BMapGL.Point(pStart.lng, pEnd.lat),
            new BMapGL.Point(pEnd.lng, pStart.lat));
        // Create a ground overlay instance
        var imgOverlay = new BMapGL.GroundOverlay(bounds, {
            type: 'image'.url: 'Picture address'.opacity: 1
        });
        // Add overlay layer to map
        map.addOverlay(imgOverlay);
Copy the code
Information window
  • Bmapgl.infowindow (text content, configuration items);
  • Generally used with custom events for other annotations
        var map = new BMapGL.Map("allmap");
        var point = new BMapGL.Point(116.404.39.925);
        map.centerAndZoom(point, 15);

        var marker = new BMapGL.Marker(point); // Create the annotation
        map.addOverlay(marker); // Add annotations to the map
        var opts = {
            width: 200.// Information window width
            height: 100.// Info window height
            title: The Palace Museum.// Info window title
        }
        var infoWindow = new BMapGL.InfoWindow(Address: 8th Floor, Lotte Intime Department Store, No. 88, Wangfujing Street, Dongcheng District, Beijing, opts); // Create an information window object
        marker.addEventListener("click".function () {
            map.openInfoWindow(infoWindow, point); // Open the info window
        });
Copy the code

Map event

  • Instance. AddEventListener (' event type ', function)Add event
  • RemoveEventListener (' event type ', function);Removed from the event
Right-click menu
  • Method of use
  1. First of all,Create a right-click menu instance new BMapGL.ContextMenu();
  2. Sets configuration items in an array
  3. Loop through an array, using each itemRight-click menu instance. AddItem (current item)Way to add to the menu
  4. Map.addcontextmenu (right-click menu instance);Adds the right-click menu item to the map instance
	var menu = new BMapGL.ContextMenu();
	var txtMenuItem = [
		{
			text:'zoom in'./ / text
			callback: function () {// Trigger the callbackmap.zoomIn(); }}, {text:'narrow'.callback: function () { map.zoomOut(); }}];for(var i = 0; i < txtMenuItem.length; i++){
		menu.addItem(new BMapGL.MenuItem(
            txtMenuItem[i].text,
            txtMenuItem[i].callback,
            100
        ));
	}
	map.addContextMenu(menu);
Copy the code

Dynamic effect

Custom perspective animation
  • Usage:
  1. Declare an animation instanceNew bmapgl. ViewAnimation(Frame animation array, configuration item);
  2. Start playing the animationMap.startviewanimation (animation instance)
  3. To stop the animationMap. cancelViewAnimation(animation instance);
You can set listening events
  • AddEventListener (‘ event type ‘, function);
  • The event type
  1. animationstartAnimation starts, if delay is configured, after delay
  2. animationiterationsWhen the animation loop is greater than 1 time, the last end is triggered when the next one starts. Does not trigger when the last loop ends
  3. animationendTriggered when the animation ends, not if the animation is terminated
  4. animationcancelTriggered when an animation has been terminated
The frame of animationAn array ofConfiguration items
  • Is an array in which each item is an object, and the configuration content is configured within each object
  • center Type Point instanceCenter point of the map. The default value is the current state center point of the map
  • zoom Type the NumberMap zoom level. The default value is the current map state zoom level
  • tilt Type the NumberTilt Angle of the map. The default value is tilt Angle of the current state of the map
  • heading Type the NumberMap rotation Angle. The default value is the current map rotation Angle
  • percentage Type the NumberIndicates the percentage of the current keyframe in the animation process. The value ranges from 0 to 1
The frame of animationThe instanceConfiguration items
  • Is an object
  • delay Type the NumberAnimation start delay, in ms, default 0
  • duration Type the NumberAnimation duration, in ms, default 1000
  • interation Type the Number | stringNumber of cycles, a fixed number of cycles if the parameter type is number. The parameter is ‘INFINITE’ and the default is 1
       var keyFrames = [{
                center: new BMapGL.Point(116.307092.40.054922),
                zoom: 20.tilt: 50.heading: 0.percentage: 0
            },
            {
                center: new BMapGL.Point(116.306858.40.057887),
                zoom: 21.tilt: 70.heading: -90.percentage: 0.35
            },
            {
                center: new BMapGL.Point(116.307904.40.058118),
                zoom: 21.tilt: 70.heading: -90.percentage: 0.45
            },
            {
                center: new BMapGL.Point(116.307092.40.054922),
                zoom: 20.tilt: 50.heading: -360.percentage: 1},];var opts = {
            duration: 10000.delay: 5000.interation: 'INFINITE'
        };

        // Declare the animation object
        var animation = new BMapGL.ViewAnimation(keyFrames, opts);
        // Listen on events
        animation.addEventListener('animationstart'.function (e) {
            console.log('start')}); map.startViewAnimation(animation);Copy the code
Path animation
  • Pay attention to: to use TrackAnimation, you need to introduce a bmapgllib. TrackAnimation library after the introduction of jsapi GL
  • Method of use
  1. To create aPolyline instance
  2. Create a trajectory animation instanceNew BMapgllib. TrackAnimation(Map instance, line instance, configuration item);
  3. Start the animationTrack animation instance. Start ();
  4. To stop the animationTrajectory animation instance. Cancel ();
Configuration items
  • For the object
  • duration Type the NumberAnimation lasts for a long time, in ms
  • delay Type the NumberAnimation start delay
  • overallView The type BooleanWhether to zoom in the overview view (adjust the map to see the entire track) after the animation is over is enabled by default
  • tilt Type the NumberSet the map tilt Angle in the animation. Default: 55 degrees
  • zoom Type the NumberSet the zoom level in the animation. By default, it will be adjusted to an appropriate level based on the trajectory

Q&A

  • Obtain the latitude and longitude of the specified area using the Boundary method