关于 mapboxgl 的常用方法及效果

给地图标记点

实现效果
在这里插入图片描述

 /**
  * 在地图上添加标记点
  * point: [lng, lat]
  * color: '#83f7a0'
  */
 addMarkerOnMap(point, color = '#83f7a0') {
   const marker = new mapboxgl.Marker({
     draggable: false,
     color: color,
   }).setLngLat(point).addTo(this.map);
   this.markersList.push(marker);
 },

给地图添加气泡展示地点详情

实现效果:
在这里插入图片描述

 /**
  * 在地图上添加气泡展示
  * point: [lng, lat]
  */
 addPopupOnMap(point) {
   // 将所选点设置为地图中心
   this.map.setCenter(point);
   // Zoom to the zoom level 8 with an animated transition
   this.map.zoomTo(16, {
     duration: 2000
   });
   // 自行赋值
   const html = `<div class="dt-popup">
     <i class="ivu-icon ivu-icon-md-close" id="closePop"></i>
     <ul>
       <li><span class="label">事件名称:</span>${eventName}</li>
       <li><span class="label">经度:</span>${longitude}</li>
       <li><span class="label">纬度:</span>${latitude}</li>
     </ul>
   </div>`
   const popup = new mapboxgl.Popup({ closeOnClick: false }).setLngLat(point).setHTML(html).addTo(this.map);
   // this.popup = popup
   Popup = popup
 },

给地图划线

实现效果
在这里插入图片描述
我的写法估计是有点问题,每条小线段都增加了一个资源和图层,但是还是实现了此功能

map.addSource(`route${routesI}`, {
  type: 'geojson',
   data: {
     type: 'Feature',
     properties: {},
     geometry: {
       type: 'LineString',
       coordinates: routesNew,
     },
   },
 });
 map.addLayer({
   id: `route${routesI}`,
   type: 'line',
   source: `route${routesI}`,
   layout: {
     'line-join': 'round',
     'line-cap': 'round',
   },
   paint: {
     'line-color': '#24C1FF',
     'line-width': 10,
   },
 });

给地图添加缓冲区画圆

实现效果:(颜色自行修改)
在这里插入图片描述

参考地址:https://blog.csdn.net/qq_33950912/article/details/127428093

思路:画圆,其实就是连接n个近似于圆的点位。

经过验证,上述文章中选取了方法三,自定义去切割圆。方法一未曾实现。方法二可能有问题,没有尝试。

/**
  * 计算以中心点、半径 缓冲区
  * center: [lng, lat]
  * radiusInKm 
  */
 createGeoJSONCircle(center, radiusInM, points = 64) {
   var coords = {
     latitude: center[1],
     longitude: center[0]
   };

   var miles = radiusInM;
   var ret = [];
   var distanceX = miles/1000/(111.320*Math.cos(coords.latitude*Math.PI/180));
   var distanceY = miles/1000/110.574;

   var theta, x, y;
   for(var i=0; i<points; i++) {
     theta = (i/points)*(2*Math.PI);
     x = distanceX*Math.cos(theta);
     y = distanceY*Math.sin(theta);

     ret.push([coords.longitude+x, coords.latitude+y]);
   }
   ret.push(ret[0]);

   return {
     "type": "geojson",
     "data": {
       "type": "FeatureCollection",
       "features": [{
         "type": "Feature",
         "geometry": {
           "type": "Polygon",
           "coordinates": [ret]
         }
       }]
     }
   };
 },

/**
	调用 - 请自行赋值
*/
map.addSource("polygon", createGeoJSONCircle([-93.6248586, 41.58527859], 0.5));
map.addLayer({
    "id": "polygon",
    "type": "fill",
    "source": "polygon",
    "layout": {},
    "paint": {
        "fill-color": "blue",
        "fill-opacity": 0.6
    }
});

给地图添加其他图片资源

实现效果
请添加图片描述
添加卡车图片资源:

 /**
 * 引入图片
  * img obj : src, name
  */
 addImage = function(img) {
   map.loadImage(img.src, (error, image) => {
     if (error) throw error;
     if (!map.hasImage(img.name)) map.addImage(img.name, image, {
       sdf: img.sdf || false
     });
   })
 }
 
// 加载 truck 
 let truck_img = {
   src: 'img/truck_mapboxgl.png',
   name: 'truck_img'
 }
 addImage(truck_img)
 

给地图添加图上gif中 1-2-3标记点并且实现鼠标滑过显示popup效果

实现效果:同上图

/**
 * 添加坐标点及鼠标以上效果
 */
addPoints = function (featuresList) {
  map.addSource('places', {
    'type': 'geojson',
    'data': {
      'type': 'FeatureCollection',
      'features': featuresList
    }
  })

  // 加载 circle 定位圆
  let img = {
    src: 'img/circle.png',
    name: 'circle_img',
    sdf: true
  }
  addImage(img)

  map.addLayer({
    'id': 'places',
    'type': 'symbol',
    'source': 'places',
    'layout': {
      'icon-image': img.name, // 图标ID
      'icon-size': 0.15, // 图标的大小
      'icon-anchor': 'center', // 图标的位置
      'text-field': ['get', 'num'],
    },
    'paint': {
      'text-color': '#fff',
      'icon-color': ['get', 'color']
    },
  });

  // Create a popup, but don't add it to the map yet.
  const popup = new mapboxgl.Popup({
    closeButton: false,
    closeOnClick: false
  });

  map.on('mouseenter', 'places', (e) => {
    // Change the cursor style as a UI indicator.
    map.getCanvas().style.cursor = 'pointer';

    // Copy coordinates array.
    const coordinates = e.features[0].geometry.coordinates.slice();
    const description = e.features[0].properties.description;

    // Ensure that if the map is zoomed out such that multiple
    // copies of the feature are visible, the popup appears
    // over the copy being pointed to.
    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
      coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

    // Populate the popup and set its coordinates
    // based on the feature found.
    popup.setLngLat(coordinates).setHTML(description).addTo(map);

  });

  map.on('mouseleave', 'places', () => {
    map.getCanvas().style.cursor = '';
    popup.remove();
  });
}

在地图中图标动态移动

实现效果:如上图

此方法用于卡车图标动态移动

/**
 * 添加路径 - 卡车图标动态效果
 */
addTruckRoutes = function (coordinatesList) {
  // 起点
  const origin = coordinatesList[0]

  const route = {
    'type': 'FeatureCollection',
    'features': [{
      'type': 'Feature',
      'geometry': {
        'type': 'LineString',
        'coordinates': coordinatesList
      }
    }]
  };

  const point = {
    'type': 'FeatureCollection',
    'features': [{
      'type': 'Feature',
      'properties': {},
      'geometry': {
        'type': 'Point',
        'coordinates': origin
      }
    }]
  }

  const lineDistance = turf.length(route.features[0]);
  const arc = [];
  const steps = 200;
  for (let i = 0; i < lineDistance; i += lineDistance / steps) {
    const segment = turf.along(route.features[0], i);
    arc.push(segment.geometry.coordinates);
  }
  route.features[0].geometry.coordinates = arc;
  let counter = 0;

  map.addSource('route', {
    'type': 'geojson',
    'data': route
  });

  map.addSource('point', {
    'type': 'geojson',
    'data': point
  });

  map.addLayer({
    'id': `route`,
    'source': 'route',
    'type': 'line',
    'paint': {
      'line-width': 20,
      'line-color': '#2d8cf0',
      'line-opacity': 0.4
    }
  })
  
  // 加载 truck 定位圆
  let truck_img = {
    src: 'img/truck_mapboxgl.png',
    name: 'truck_img'
  }
  addImage(truck_img)

  map.addLayer({
    'id': `point`,
    'source': 'point',
    'type': 'symbol',
    'layout': {
      'icon-image': truck_img.name,
      'icon-size': 0.2,
      'icon-rotate': ['get', 'bearing'],
      'icon-rotation-alignment': 'map',
      'icon-allow-overlap': true,
      'icon-ignore-placement': true
    }
  });

  animate = function () {
    running = true;
    const start =
      route.features[0].geometry.coordinates[
        counter >= steps ? counter - 1 : counter
      ];
    const end =
      route.features[0].geometry.coordinates[
        counter >= steps ? counter : counter + 1
      ];
    point.features[0].geometry.coordinates =
      route.features[0].geometry.coordinates[counter];
    point.features[0].properties.bearing = turf.bearing(
      turf.point(start),
      turf.point(end)
    )+90; // 此处控制图标的头部指向问题,可以加减角度,使卡车头部一直朝着目的地

    // Update the source with this new data
    map.getSource('point').setData(point);

    // Request the next frame of animation as long as the end has not been reached
    if (counter < steps) {
      requestAnimationFrame(animate);
      counter = counter + 1;
    } else {
      counter = 0
      animate()
    }      
  }

  animate(counter);
}

地图路线持续闪动特效

实现效果
请添加图片描述
此方法官网有示例

代码如下:

/**
 * 添加路径 - 路径虚线变化效果
 */
addDashedRoutes = function (coordinatesList) {
  map.addSource('route', {
    'type': 'geojson',
    'data': {
      'type': 'Feature',
      'properties': {},
      'geometry': {
        'type': 'LineString',
        'coordinates': coordinatesList
      }
    }
  });
  map.addLayer({
    'id': 'route',
    'type': 'line',
    'source': 'route',
    'layout': {
      'line-join': 'round',
      'line-cap': 'round'
    },
    'paint': {
      // 'line-color': '#2b85e4',
      // 'line-width': 10
      'line-color': '#2d8cf0',
      'line-width': 8,
      'line-opacity': 0.4
    }
  });
  map.addLayer({
    id: 'line-dashed',
    type: 'line',
    source: 'route',
    paint: {
      'line-color': '#2db7f5',
      'line-width': 8,
      'line-dasharray': [0, 4, 3]
    }
  });   

  /**
   * 动态展示路径 - 路径虚线变化效果
   */
  const dashArraySequence = [
    [0, 4, 3],
    [0.5, 4, 2.5],
    [1, 4, 2],
    [1.5, 4, 1.5],
    [2, 4, 1],
    [2.5, 4, 0.5],
    [3, 4, 0],
    [0, 0.5, 3, 3.5],
    [0, 1, 3, 3],
    [0, 1.5, 3, 2.5],
    [0, 2, 3, 2],
    [0, 2.5, 3, 1.5],
    [0, 3, 3, 1],
    [0, 3.5, 3, 0.5]
  ];
  let step = 0;
  animateDashArray = function (timestamp) {
    const newStep = parseInt(
      (timestamp / 50) % dashArraySequence.length
    );

    if (newStep !== step) {
      map.setPaintProperty(
        'line-dashed',
        'line-dasharray',
        dashArraySequence[step]
      );
      step = newStep;
    }

    // Request the next frame of the animation.
    requestAnimationFrame(animateDashArray);
  }

  // start the animation
  animateDashArray(0);
}  

地图正向反向地址匹配

官网有示例,可自行查阅

/**
 * 正向地址匹配
 * address: '孵化大厦'
 */
addressMatchPoint(address) {
  // 正向匹配参数
  var geoCodeParam = new SuperMap.GeoCodingParameter({
    address: address, // 地址
    fromIndex:0, // 设置返回对象的起始索引值
    toIndex:10, // 设置返回对象的结束索引值。
    // prjCoordSys:{epsgcode26}, // 坐标设置
    maxReturn:5 // 最大返回结果数
  });
  //创建地址匹配服务
  var addressUrl = MAP_SERVICE + "***************"
  var addressMatchService = new mapboxgl.supermap.AddressMatchService(addressUrl);
  // 向服务端发送请求进行正向地址匹配,并获取返回的结果
  return addressMatchService.code(geoCodeParam, function(obj){});
},

/**
 * 反向地址匹配
 * point: [lng, lat]
 */
pointMatchAddress(point) {
  // 反向匹配参数
  var geoDecodeParam = new SuperMap.GeoDecodingParameter({
    x: point[0], // 横坐标
    y: point[1], // 纵坐标
    fromIndex: 0, // 设置返回对象的起始索引值。
    toIndex: 10, // 设置返回对象的结束索引值。
    // filters: "", // 过滤字段
    // prjCoordSys: {epsgcode26}, // 坐标设置
    maxReturn: 3, // 最大结果数
    geoDecodingRadius: -1 // 查询半径
  });
  // 创建地址匹配服务
  var addressUrl = MAP_SERVICE +  "***************"
  var addressMatchService = new mapboxgl.supermap.AddressMatchService(addressUrl);
  // 向服务端发送请求进行反向地址匹配,并获取返回的结果
  return addressMatchService.decode(geoDecodeParam, function(obj){});
},

两点之间路径规划

参照官网示例

let serviceUrl = MAP_SERVICE + '******';
let findPathService = new mapboxgl.supermap.NetworkAnalystService(serviceUrl);
//向服务器发送请求,并对返回的结果进行分析处理,展示在客户端上
const result = findPathService.findPath(findPathParams, function(serviceResult) {})
// ...不完整代码

遇到问题

  1. 在vue组件中,添加上了maker或者popup,使用data中定义变量会造成地图空白问题,暂时没有解决,后面改用在全局声明marker或者popup,layer好像也存在类似问题,可以参考解决。
    在这里插入图片描述
  2. 调用以上方法包裹在 map.on('load', () => { }) 的方法中。
  3. 以上代码均为不完整代码,有些在vue中使用,有些在原生中使用,请仔细阅读,以免出错。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/222927.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

从【注意力机制】开始的,零基础【大模型】系列

注意力机制 原理&#xff1a;从关注全部到关注重点软注意力-计算方式传统注意力问题 键值注意力&#xff1a;单标签的检索系统计算方式 多头注意力&#xff1a;多标签的检索系统自注意力&#xff1a;对输入数据内部关系进行预处理计算方式 Transformer 原理&#xff1a;从关注全…

医院预约挂号平台的设计与实现

摘 要 网络的空前发展给人们的工作和生活带来了极大的便利&#xff0c;信息技术已成为节约运营成本、提高工作效率的首选。相比之下&#xff0c;国内相当多的中小医院在医院预约工作中的手工工作比较保守&#xff0c;数据查询和存储成本都很高&#xff0c;但效率很低。为了使医…

docker-compose部署sonarqube 8.9 版本

官方部署文档注意需求版本 所以选择8.9版本 一、准备部署配置 1、持久化目录 rootlocalhost:/root# mkdir -p /data/sonar/postgres /data/sonar/sonarqube/data /data/sonar/sonarqube/logs /data/sonar/sonarqube/extensions rootlocalhost:/root# chmod 777 /data/sona…

天眼销为电销行业降低获客成本

当下&#xff0c;做电销的老板都有一个深刻体会&#xff1a;市场竞争越来越激烈&#xff0c;获客成本不断攀升&#xff0c;但效率不升返降&#xff0c;企业经营困难。特别是在这一两年&#xff0c;市场环境紧张&#xff0c;业务不好开展&#xff0c;更是雪上加霜。 销售也感觉…

Matlab 曲线动态绘制

axes(handles.axes1); % 选定所画坐标轴 figure也可 h1 animatedline; h1.Color b; h1.LineWidth 2; h1.LineStyle -; % 线属性设置 for i 1 : length(x)addpoints(h1,x(i),y(i)); % x/y为待绘制曲线数据drawnow;pause(0.01); % 画点间停顿 end 示例&#xff1a; figure…

BearPi Std 板从入门到放弃 - 引气入体篇(8)(ADC)

简介 基于前面的文章, 缩略STM32CubeMx创建项目的过程&#xff0c;直接添加ADC相关初 始化; 开发板 &#xff1a; Bearpi Std(小熊派标准板) 主芯片: STM32L431RCT6 LED : PC13 \ 推挽输出即可 \ 高电平点亮 串口: Usart1 ADC1: PC2步骤 创建STM32CubeMX LED/串口ADC1初始…

「音视频处理」音频编码AAC详解,低码率提高音质?

AAC&#xff08;高级音频编码&#xff09; 也称为 MPEG-4 音频。数码音频压缩和编码的标准方式。AAC 编码文件可与音乐光盘的质量相匹敌&#xff0c;且声音质量通常等同于或高于以相同或甚至更高的位速率编码的 MP3 文件。 我们按这样的顺序讨论 &#xff1a; 1、 封装格式的…

如何使用 Zotero 导出所选条目的 PDF 文件

如何使用 Zotero 导出所选条目的 PDF 文件 Zotero 是一款强大的参考文献管理工具&#xff0c;但它并不直接提供将整个文件夹导出为 PDF 的选项。不过&#xff0c;您可以使用以下步骤来导出您所选的 Zotero 条目中的 PDF 文件&#xff0c;无需额外的插件。 选择所需的 Zotero 条…

2023年危险化学品生产单位安全生产管理人员证考试题库及危险化学品生产单位安全生产管理人员试题解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2023年危险化学品生产单位安全生产管理人员证考试题库及危险化学品生产单位安全生产管理人员试题解析是安全生产模拟考试一点通结合&#xff08;安监局&#xff09;特种作业人员操作证考试大纲和&#xff08;质检局&a…

二叉树链式结构

1.前置说明 我们手动构建一棵二叉树&#xff1a; 注意&#xff1a;上述代码并不是创建二叉树的方式 从概念中可以看出&#xff0c;二叉树定义是递归式的&#xff0c;因此后序基本操作中基本都是按照该概念实现的 2.二叉树的遍历 2.1前序、中序以及后序遍历 学习二叉树结构&a…

基于c++版本链队列改-Python版本链队列基础理解

##基于链表的队列实现 可以将链表的“头节点”和“尾节点”分别视为“队首”和“队尾”&#xff0c;规定队尾仅可添加节点&#xff0c;队首仅可删除节点。 ##图解 ##基于链表的队列实现代码 class ListNode:"""定义链表"""def __init__(self)…

Nexus搭建npm私库(角色管理、上传脚本)

安装Nexus 官网下载 https://www.sonatype.com/products/sonatype-nexus-oss-download 进入官网下载&#xff0c;最新下载方式需要输入个人信息才能下载了 选择对应的系统进行下载 Windows 推荐也下载 UNIX 版本&#xff08;Windows 版本配置比较难改&#xff09; 如果没有下…

​LeetCode解法汇总2477. 到达首都的最少油耗

目录链接&#xff1a; 力扣编程题-解法汇总_分享记录-CSDN博客 GitHub同步刷题项目&#xff1a; https://github.com/September26/java-algorithms 原题链接&#xff1a;力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台 描述&#xff1a; 给你一棵 …

org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource

DynamicDataSource-CSDN博客 /** Copyright 2002-2020 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the L…

排序算法基本原理及实现2

&#x1f4d1;打牌 &#xff1a; da pai ge的个人主页 &#x1f324;️个人专栏 &#xff1a; da pai ge的博客专栏 ☁️宝剑锋从磨砺出&#xff0c;梅花香自苦寒来 &#x1f324;️冒泡排序 &#x1…

解决mybatis-plus中,当属性为空的时候,update方法、updateById方法无法set null,直接忽略了

问题描述 当indexId set 22的时候是可以set的 我们发现sql语句也是正常的 表中数据也被更改了 但是当我们indexId为空的时候 sql语句中没有了set indexId这一属性。。 既然属性都没了&#xff0c;表是肯定没做修改的 问题解决 在实体类对应的字段上加注解TableField(strategy…

每日一练【有效三角形的个数】

一、题目描述 611. 有效三角形的个数 给定一个包含非负整数的数组 nums &#xff0c;返回其中可以组成三角形三条边的三元组个数。 示例 1: 输入: nums [2,2,3,4] 输出: 3 解释:有效的组合是: 2,3,4 (使用第一个 2) 2,3,4 (使用第二个 2) 2,2,3示例 2: 输入: nums [4,2…

《WebGIS快速开发教程》第5版“惊喜”更新啦

我的书籍《WebGIS快速开发教程》第5版&#xff0c;经过忙碌的编写&#xff0c;终于发布啦&#xff01; 先给大家看看新书的封面&#xff1a; 这次的封面我们经过了全新的设计&#xff0c;不同于以往的任何一个版本。从封面就可以看出第5版肯定有不小的更新。 那么我们话不多说…

ChatGPT,作为一种强大的自然语言处理模型,具备显著优势,能够帮助您在各个领域取得突破

2023年随着OpenAI开发者大会的召开&#xff0c;最重磅更新当属GPTs&#xff0c;多模态API&#xff0c;未来自定义专属的GPT。微软创始人比尔盖茨称ChatGPT的出现有着重大历史意义&#xff0c;不亚于互联网和个人电脑的问世。360创始人周鸿祎认为未来各行各业如果不能搭上这班车…

Linux服务器部署XXL-JOB

参考文档及下载地址&#xff1a;分布式任务调度平台XXL-JOB 1 从git拉取XXL-JOB代码 我们的大部分变动&#xff0c;是发生在xxl-job-admin&#xff0c;最终将这个模块打包成jar包部署在linux服务器上。 2 执行数据库脚本 doc\db\tables_xxl_job.sql 3 修改pom文件&#xff0c…
最新文章