Introduction to the

Realize the function of track playback on AMAP with native JS in the Web browser, and update the detailed coordinate information in real time during the playback

Results the GIF

source

Website demo

The demo on the official website has added a small popover to display information, which is realized by updating information to the DOM in real time when the truck is moving

Implementation steps

  1. Introduced gaudamap JS
<script src="https://webapi.amap.com/maps?v=1.4.15&key=" + "Key value requested by yourself"></script>
Copy the code
  1. Draw the HTML
<body>
    <div id="container">
        <div id="btn-card">
            <span class="operate">Track playback:</span>
            <button class="btn" onclick="start()">start</button>
            <button class="btn" onclick="pause()">suspended</button>
            <button class="btn" onclick="reset()">reset</button>
        </div>
    </div>
    <div id="tips">
        <span id="license"></span>
        <span id="speed"></span>
        <span id="longitude"></span>
        <span id="latitude"></span>
        <span id="time"></span>
    </div>
</body
Copy the code
  1. Simulate background data to create map elements
<script>
// This is the data returned by the simulation background, including the specific information of each point
var data = [
    { longitude: 116.478935.latitude: 39.997761.license: 'shan KE1675'.speed: '57.2 KM/H'.time: 'the 2021-06-07 16:21:12' },
    { longitude: 116.478939.latitude: 39.997825.license: 'shan KE1675'.speed: '56.5 KM/H'.time: 'the 2021-06-07 16:25:21' },
    { longitude: 116.478912.latitude: 39.998549.license: 'shan KE1675'.speed: '48.3 KM/H'.time: 'the 2021-06-07 16:51:28' },
    { longitude: 116.479282.latitude: 39.998561.license: 'shan KE1675'.speed: '65.6 KM/H'.time: 'the 2021-06-07 17:21:30' },
    { longitude: 116.479658.latitude: 39.998528.license: 'shan KE1675'.speed: '39.1 KM/H'.time: 'the 2021-06-07 17:20:38' },
    { longitude: 116.480151.latitude: 39.998453.license: 'shan KE1675'.speed: '53.7 KM/H'.time: 'the 2021-06-07 19:01:42' },
    { longitude: 116.482362.latitude: 39.997718.license: 'shan KE1675'.speed: '57.8 KM/H'.time: 'the 2021-06-07 20:31:45' },
    { longitude: 116.483633.latitude: 39.998935.license: 'shan KE1675'.speed: '59.1 KM/H'.time: 'the 2021-06-07 21:28:50' },
    { longitude: 116.483671.latitude: 39.998968.license: 'shan KE1675'.speed: '70.2 KM/H'.time: 'the 2021-06-07 22:45:58' },
    { longitude: 116.484648.latitude: 39.999861.license: 'shan KE1675'.speed: '68.6 KM/H'.time: 'the 2021-06-07 23:23:00'}]/ * constructor is introduced: AMap. LngLat (LNG: Number, lat: Number, noAutofix: bool) : construct a geographic coordinate object LNG, lat represent the latitude and longitude values; NoAutoFix specifies whether the longitude is automatically corrected to the range [-180,180]. The default value is false. Amap. Pixel(x:Number,y:Number): constructs a Pixel coordinate object in the x direction and the y direction */

/** * Map: map container * marker: moving cars * lineArr: coordinate array of track nodes * Polyline: whole track * passedPolyline: moved track * infoTip: information display tips */
var map, marker, lineArr, polyline, passedPolyline, infoTip;
// Whether it is currently moving
var movingFlag = false;
initMap(data);
function initMap(data) {
    lineArr = data.map(item= > [item.longitude, item.latitude]);
    map = new AMap.Map('container', {
        // Boolean: Whether to monitor map container size changes. Default is false
        resizeEnable: true.// LngLat: map center position value, array type format also works
        center: [116.397428.39.90923].// Number: map display zoom level, if center and level are not set, map initialization default display user's city range
        zoom: 11
    });

    // Create a car
    marker = new AMap.Marker({
        // Map: Map object to display this marker
        map: map,
        // LngLat: indicates the location displayed on the map. The default is the center of the map
        Position: new amap.lnglat (116.478935, 39.997761),
        position: lineArr[0].// String/Icon: the Icon to be displayed in the dot mark. It can be a local Icon address or an Icon object. This property is invalid if there is legal content
        icon: "https://webapi.amap.com/images/car.png"./* Pixel: The default value is Pixel(-10,-34). After position is specified by Marker, the position at the upper left corner of Marker is taken as the reference point by default to align with the given position. If the specified position of Marker is to be aligned at position, A certain offset */ should be set according to the size of marker
        offset: new AMap.Pixel(-26, -13),
        // Boolean: Whether to rotate automatically. The dot mark automatically adjusts the Angle when the path direction changes when using moveAlong animation. The default is false. Widely used to automatically adjust the direction of the vehicle
        autoRotation: true.// Number: the rotation Angle of the dot mark, widely used to change the direction of the vehicle
        angle: -90});// Draw the entire trajectory
    polyline = new AMap.Polyline({
        // Map: The Map object to display for the polyline
        map: map,
        // Array: Array of node coordinates of the polyline
        path: lineArr,
        // Boolean: Specifies whether to display white directional arrows along the path. Default is false. Canvas is valid for drawing. It is recommended to use Canvas when the width of broken line is greater than 6
        showDir: true.// String: line color, assigned by hexadecimal color code. The default is #006600
        strokeColor: "#28F".// Number: line transparency. The value ranges from 0 to 1, where 0 indicates full transparency and 1 indicates opacity. The default is 0.9
        strokeOpacity: 1.// Number: line width, in pixels
        strokeWeight: 6.// String: line style, solid line :solid, dashed line :dashed line
        strokeStyle: "solid"
    });

    // Create information to display tip
    infoTip = new AMap.InfoWindow({
        isCustom: true.// Use custom forms
        content: document.getElementById('tips'),
        offset: new AMap.Pixel(16, -45)});// The path that has been moved
    passedPolyline = new AMap.Polyline({
        map: map,
        strokeColor: "#AF5".strokeWeight: 6.strokeStyle: "dashed"
    });
}
</script>
Copy the code
  1. User behavior control, listening for movement events
<script>
function start() {
    if(! movingFlag) {/* moveAlong(path:Array, speed:Number, f:Function, circlable:Boolean) moveAlong(path:Array, speed:Number, f:Function, circlable:Boolean) Path: an array of latitude and longitude objects for the path; The default value is function(k){return k} circlable: indicates whether the animation is executed in a loop. The default value is false */
        marker.moveAlong(lineArr, 500);
        movingFlag = true;
    } else {
        // Restore the animation effect of the dot markersmarker.resumeMove(); }}function pause() {
    if (movingFlag) {
        // The animation effect of the temporary markingmarker.pauseMove(); }}function reset() {
    if (movingFlag) {
        // Close the popover
        infoTip.close();
        // return to the initial position
        marker.setPosition([116.478935.39.997761]);
        marker.stopMove();
        // Clear the track that has moved
        passedPolyline.setPath([]);
        movingFlag = false; }}/* Monitor movement events: The point Marker triggers the event when executing the moveTo, moveAlong animation. The format of e is {passedPath:Array
      
       } where passedPath is the path that the Marker has taken during moveAlong or moveTo */
      
marker.on('moving'.function (e) {
    // setPath: Sets the array of nodes that make up the line
    passedPolyline.setPath(e.passedPath);
    var length = e.passedPath.length;
    // console.log(length, e.passedPath); You can print it and see the structure
    // Update information on the move
    document.getElementById('tips').style.display = 'flex';
    document.getElementById('license').innerText = 'License plate number:' + data[length - 1].license;
    document.getElementById('speed').innerText = 'Speed:' + data[length - 1].speed;
    document.getElementById('longitude').innerText = 'Longitude:' + data[length - 1].longitude;
    document.getElementById('latitude').innerText = 'Latitude:' + data[length - 1].latitude;
    document.getElementById('time').innerText = 'Time:' + data[length - 1].time;
    infoTip.open(map, marker.getPosition());
});

/* setFitView(overlayList:Array/null, immediately:bool, avoid:[Number,Number,Number,Number], MaxZoom :Number) automatically scales the map to an appropriate view level according to the distribution of the added coverings on the map. OverlayList: indicates the array of coverings, and the default is immediately of all coverings added on the current map: Avoid: Represents the pixel avoidance width of the upper, lower, and left maxZoom: represents the maximum level after fitView */
map.setFitView();
</script>
Copy the code
  1. The style file
#container {
    position: relative;
    margin: 0 auto;
    width: 800px;
    height: calc(100vh - 50px);
}

#btn-card {
    display: flex;
    justify-content: space-evenly;
    position: absolute;
    bottom: 10px;
    right: 10px;
    align-items: center;
    width: 280px;
    height: 60px;
    background-color: #fff;
    background-clip: border-box;
    box-shadow: 0 2px 6px 0 gray;
    z-index: 999;
    padding: 0 10px;
}

.operate {
    font-size: 12px;
}

.btn {
    padding: 2px 15px;
    color: #25A5F7;
    border: 1px solid #25A5F7;
    background-color: transparent;
    border-radius: 10px;
    cursor: pointer;
}

.btn:hover {
    color: #fff;
    background-color: #25A5F7;
}

#tips {
    height: 100px;
    width: 180px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 5px;
    background: #fff;
    border: 1px solid #DEDEDD;
    border-radius: 10px;
    font-size: 12px;
    display: none;
}
Copy the code

conclusion

First time to write an article, the first time to use the Amap API, if there is an error please correct