search
HomeWeb Front-endJS TutorialHow to create a logistics map in D3.js (detailed tutorial)

This article mainly introduces the sample code for using D3.js to create a logistics map. Now I share it with you and give it as a reference.

This article introduces the sample code for creating a logistics map using D3.js and shares it with everyone. The details are as follows:

Sample map

Production Ideas

  1. #You need to draw a map of China as the background.

  2. The latitude and longitude coordinates of major cities are required to draw the starting and ending points of road sheets.

  3. The city that receives the logistics order draws a flashing mark.

  4. The target city that already has a logistics order will no longer draw a route.

  5. Every time a new logistics order is generated, there will be an animation effect of the mark moving along the route to the target.

  6. The data after drawing needs to be cleaned up to reduce the resource usage of the browser.

Start coding

1. Create a web page template

Load D3JS for easy debugging , directly download the d3.js file locally. When actually using it, you can change it to the loading path. Note that the V4 version of D3 is used, which is different from the V3 version.

Create a p block and prepare it for drawing.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf8">
    <script type="text/javascript" src="../../static/d3/d3.js"></script>
    <title>地图</title>
  </head>
  <body>
    <p class="fxmap">
    </p>
  </body>
  <script type="text/javascript"></script>
</html>

Create SVG, all the following codes are placed in <script></script>

var width=1000 , height=800; // 定义SVG宽高
var svg = d3.select("body p.fxmap")
            .append("svg")
            .attr("width", "width) 
            .attr("height", height)
            .style("background","#000"); //

Create SVG graphics grouping in preparation for calling

  1. gmp, save the background map and starting point marker.

  2. mline, saves the connection between the starting point and the target, as well as the target point.

  3. button, button for testing

gmap = svg.append("g").attr("id", "map").attr("stroke", "white").attr("stroke-width",1);
    mline = svg.append("g").attr("id", "moveto").attr("stroke", "#FFF").attr("stroke-width", 1.5).attr("fill","#FFF");
    button = svg.append("g").attr("id", "button").attr("stroke", "white").attr("stroke-width", 1).attr("fill", "white");

Create projection function

  1. Longitude and latitude cannot be used directly for drawing and need to be converted into plane coordinates. d3js provides a relatively rich range of projection methods. In this example, the geoEquirectangular() method is used.

  2. projection is a method to convert longitude and latitude into plane coordinates

  3. path is a method to convert longitude and latitude into line drawing point coordinates (save yourself Then write the function to construct the path path)

var projection = d3.geoEquirectangular()
              .center([465,395]) // 指定投影中心,注意[]中的是经纬度
              .scale(height)
              .translate([width / 2, height / 2]);
var path = d3.geoPath().projection(projection);

Create a marker so that multiple connection endpoints can be called

  1. Because There will be multiple end points of the logistics line, so they are all called in a marker.

  2. This mark is composed of a circular outer ring in the middle. The flashing effect of the outer ring is created separately.

marker = svg.append("defs")
          .append("marker")
          .append("marker")
          .attr("id", "pointer")
          .attr("viewBox","0 0 12 12")  // 可见范围
          .attr("markerWidth","12")    // 标记宽度
          .attr("markerHeight","12")    // 标记高度
          .attr("orient", "auto")     //
          .attr("markerUnits", "strokeWidth") // 随连接线宽度进行缩放
          .attr("refX", "6")       // 连接点坐标
          .attr("refY", "6")
    // 绘制标记中心圆
    marker.append("circle")
        .attr("cx", "6")
        .attr("cy", "6")
        .attr("r", "3")
        .attr("fill", "white");
    // 绘制标记外圆,之后在timer()中添加闪烁效果
    marker.append("circle")
        .attr("id", "markerC")
        .attr("cx", "6")
        .attr("cy", "6")
        .attr("r", "5")
        .attr("fill-opacity", "0")
        .attr("stroke-width", "1")
        .attr("stroke", "white");

Draw a map of China and mark the starting point (Changsha)

The longitude and latitude set used in the map is china.json. There are many files on the Internet

// 记录长沙坐标
    var changsha = projection([112.59,28.12]);
    // 读取地图数据,并绘制中国地图
    mapdata = [];
    d3.json(&#39;china.json&#39;, function(error, data){
      if (error)
        console.log(error);
      // 读取地图数据
      mapdata = data.features;
      // 绘制地图
      gmap.selectAll("path")
        .data(mapdata)
        .enter()
        .append("path")
        .attr("d", path);
      // 标记长沙
      gmap.append("circle").attr("id","changsha")
        .attr("cx", changsha[0])
        .attr("cy", changsha[1])
        .attr("r", "6")
        .attr("fill", "yellow")
      gmap.append("circle").attr("id","changshaC")
        .attr("cx", changsha[0])
        .attr("cy", changsha[1])
        .attr("r", "10")
        .attr("stroke-width", "2")
        .attr("fill-opacity", "0");
    });

Create a method to draw a line from the specified starting point to the end point, and draw markers at the network points.

  1. The method requires inputting the destination city name (city) and latitude and longitude (data)

  2. Call the previously established project() method. Convert the end point latitude and longitude into plane coordinates.

  3. Calculate the distance between the starting point (Changsha) and the end point as line length and animation time parameters.

  4. Draw a circular mark on the line and animate the movement from the starting point to the end point.

  5. After the mark is moved to the end point, it will be deleted to save resources.

  6. If the line point has been drawn before, no line will be drawn, only the moving mark will be drawn.

  7. Every time a logistics order is processed, the city record is 1.

// 创建对象,保存每个城市的物流记录数量
    var citylist = new Object();
    // 创建方法,输入data坐标,绘制发射线
    var moveto = function(city, data){
      var pf = {x:projection([112.59,28.12])[0], y:projection([112.59,28.12])[1]};
      var pt = {x:projection(data)[0], y:projection(data)[1]};
      var distance = Math.sqrt((pt.x - pf.x)**2 + (pt.y - pf.y)**2);
      if (city in citylist){
        citylist[city]++;
      }else{
        mline.append("line")
            .attr("x1", pf.x)
            .attr("y1", pf.y)
            .attr("x2", pt.x)
            .attr("y2", pt.y)
            .attr("marker-end","url(#pointer)")
            .style("stroke-dasharray", " "+distance+", "+distance+" ")
            .transition()
            .duration(distance*30)
            .styleTween("stroke-dashoffset", function(){
              return d3.interpolateNumber(distance, 0);
            });
        citylist[city] = 1;
      };
      mline.append("circle")
        .attr("cx", pf.x)
        .attr("cy", pf.y)
        .attr("r", 3)
        .transition()
        .duration(distance*30)
        .attr("transform", "translate("+(pt.x-pf.x)+","+(pt.y-pf.y)+")")
        .remove();
    };

Create an animation queue example to achieve the flashing effect of the outer circle of the mark

var scale = d3.scaleLinear();
    scale.domain([0, 1000, 2000])
      .range([0, 1, 0]);
    var start = Date.now();
    d3.timer(function(){
      var s1 = scale((Date.now() - start)%2000);
      // console.log(s1);
      gmap.select("circle#changshaC")
        .attr("stroke-opacity", s1);
      marker.select("circle#markerC")
        .attr("stroke-opacity", s1);
    });

Create a test button and test target city data

var cityordinate = {
      &#39;哈尔滨&#39;:[126.5416150000,45.8088260000],
      &#39;石家庄&#39;:[116.46,39.92],
      &#39;北京&#39;:[116.39564503787867,39.92998577808024],
      &#39;上海&#39;:[121.480539,31.235929],
      &#39;广州&#39;:[113.271431,23.135336],
      &#39;重庆&#39;:[106.558434,29.568996],
      &#39;青岛&#39;:[120.38442818368189,36.10521490127382],
      &#39;福州&#39;:[119.30347,26.080429],
      &#39;兰州&#39;:[103.840521,36.067235],
      &#39;贵阳&#39;:[106.636577,26.653325],
      &#39;成都&#39;:[104.081534,30.655822],
      &#39;西安&#39;:[108.946466,34.347269],
      &#39;长春&#39;:[125.3306020000,43.8219540000],
      &#39;台湾&#39;:[120.961454,23.80406],
      &#39;呼和浩特&#39;:[111.7555090000,40.8484230000],
      &#39;澳门&#39;:[113.5494640000,22.1929190000],
      &#39;武汉&#39;:[114.3115820000,30.5984670000],
      &#39;昆明&#39;:[102.71460113878045,25.049153100453159],
      &#39;乌鲁木齐&#39;:[87.56498774111579,43.84038034721766],
      &#39;益阳&#39;:[112.36654664522563,28.58808777988717],
      &#39;南京&#39;:[118.77807440802562,32.05723550180587],
      &#39;武昌&#39;:[114.35362228468498,30.56486029278519],
    };

    // 随机获得目标城市
    var cityname = [], total = 0;
    for (var key in cityordinate){
      cityname[total++] = key;
    };
    
    // 创建操作按钮,每次点击发射一条物流线
    button.append("circle")
        .attr("cx", width*0.9)
        .attr("cy", height*0.8)
        .attr("r", width/20)
        .attr("text","click")
        .attr("fill", "grey");
    button.append("text")
        .attr("x", width*0.87)
        .attr("y", height*0.81)
        .style("font-size", "30px")
        .text("click");
    button.on("click", function(){
      var _index = ~~(Math.random() * total);
      moveto(cityname[_index], cityordinate[cityname[_index]]);
    });

The above is I compiled it for everyone, I hope it will be helpful to everyone in the future.

Related articles:

How to implement map grid using Baidu Maps

Comparison and distinction between Express and Koa2 in nodejs (detailed tutorial)

The singleton mode in JS implements data addition, deletion, modification and query

The above is the detailed content of How to create a logistics map in D3.js (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

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
如何在iPhone中使Google地图成为默认地图如何在iPhone中使Google地图成为默认地图Apr 17, 2024 pm 07:34 PM

iPhone上的默认地图是Apple专有的地理位置提供商“地图”。尽管地图越来越好,但它在美国以外的地区运行不佳。与谷歌地图相比,它没有什么可提供的。在本文中,我们讨论了使用Google地图成为iPhone上的默认地图的可行性步骤。如何在iPhone中使Google地图成为默认地图将Google地图设置为手机上的默认地图应用程序比您想象的要容易。请按照以下步骤操作–先决条件步骤–您必须在手机上安装Gmail。步骤1–打开AppStore。步骤2–搜索“Gmail”。步骤3–点击Gmail应用旁

如何在uniapp中使用地图和定位功能如何在uniapp中使用地图和定位功能Oct 16, 2023 am 08:01 AM

如何在uniapp中使用地图和定位功能一、背景介绍随着移动应用的普及和定位技术的迅猛发展,地图和定位功能已经成为了现代移动应用中不可缺少的一部分。uniapp是一种基于Vue.js开发的跨平台应用开发框架,可以方便开发者在多个平台上共用代码。本文将介绍如何在uniapp中使用地图和定位功能,并提供具体的代码示例。二、使用uniapp-amap组件实现地图功能

小红书如何把店铺地址加入地图?店铺地址设置怎么填?小红书如何把店铺地址加入地图?店铺地址设置怎么填?Mar 29, 2024 am 09:41 AM

随着小红书越来越受到年轻人的喜爱,越来越多的人选择在小红书上开店。许多新手卖家在设置店铺地址时遇到了困难,不知道如何把店铺地址加入地图。一、小红书如何把店铺地址加入地图?1.首先,确保您的店铺在小红书上有注册账号,并且已经成功开设店铺。2.登录小红书账号,进入店铺后台,找到“店铺设置”选项。3.在店铺设置页面,找到“店铺地址”一栏,点击“添加地址”。4.在弹出的地址添加页面,填写店铺的详细地址信息,包括省份、城市、区县、街道、门牌号等。5.填写完毕后,点击“确认添加”按钮。小红书会对您提供的地址

如何使用Highcharts创建地图热力图如何使用Highcharts创建地图热力图Dec 17, 2023 pm 04:06 PM

如何使用Highcharts创建地图热力图,需要具体代码示例热力图是一种可视化的数据展示方式,能够通过不同颜色深浅来表示各个区域的数据分布情况。在数据可视化领域,Highcharts是一个非常受欢迎的JavaScript库,它提供了丰富的图表类型和交互功能。本文将介绍如何使用Highcharts创建地图热力图,并提供具体的代码示例。首先,我们需要准备一些数据

掌握 iPhone 和 iPad 上 Apple 地图指南的使用技巧掌握 iPhone 和 iPad 上 Apple 地图指南的使用技巧Aug 30, 2023 am 09:25 AM

在不断发展的技术世界中,导航数字地图的能力已成为一项基本技能。本文提供了有关如何在iPhone和iPad上使用Apple地图指南的综合指南,该功能彻底改变了用户探索周围环境和计划旅程的方式。Apple地图是所有Apple设备上的内置应用程序,它不断更新和改进,以提供无缝导航体验。它最显着的功能之一是“指南”功能,它提供了世界各地各个城市有趣景点的精选列表。此功能不仅对旅行者有利,而且对希望在自己城市中发现新景点的当地人来说也是福音。如何在iOS上使用Apple地图指南首先,访问Apple地图上的

如何在谷歌地图上使用一目了然的方向如何在谷歌地图上使用一目了然的方向Jun 13, 2024 pm 09:40 PM

在发布一年后,谷歌地图推出了一项新的功能。一旦您在地图上设置了目的地的路线,它就会总结您的旅行路线。旅程开始后,您可以从手机锁定屏幕“浏览”路线导航。您可以使用Google地图来查看您的预计到达时间和路线。在整个旅行期间,您可以在锁定屏幕上查看导航信息,通过解锁手机,无需访问Google地图即可查看导航信息。通过解锁手机,无需访问Google地图即可查看导航信息。通过解锁手机,无需访问Google地图,您即可查看导航信息,解锁手机,无需访问Google地图,您即可查看导航信息,解锁手机,无需访问

云端车端MapNeXt全搞定!面向下一代在线高精地图构建云端车端MapNeXt全搞定!面向下一代在线高精地图构建Jan 31, 2024 pm 06:06 PM

写在前面&笔者的个人理解在协作、互联和自动化移动(CCAM)中,智能驾驶车辆对周围环境的感知、建模和分析能力越强,它们就越能意识到并能够理解、做出决策,以及安全高效地执行复杂的驾驶场景。高精(HD)地图以厘米级精度和车道级语义信息表示道路环境,使其成为智能移动系统的核心组件,也是CCAM技术的关键推动者。这些地图为自动化车辆提供了了解周围环境的强大优势。高精地图也被视为隐藏的或虚拟的传感器,因为它汇集了来自物理传感器的知识(地图),即激光雷达、相机、GPS和IMU,以建立道路环境的模型。高精地图

如何下载iPhone地图以供离线使用如何下载iPhone地图以供离线使用Nov 04, 2023 pm 11:13 PM

随着iOS17的推出,Apple使iPhone用户可以下载地图以供离线使用。此功能为可能前往互联网连接不可靠或不存在的地区的用户提供了实用的解决方案。通过将地图下载到他们的设备上,用户可以确保即使失去蜂窝连接,他们也可以始终访问他们想要的路线。离线地图不仅仅是一个位置的静态图像。它们为用户提供了丰富的信息,例如地点的小时数和评级、转弯路线和预计到达时间。这意味着即使没有Wi-Fi或蜂窝连接,用户仍然可以导航和访问有关周围环境的关键信息。在“地图”中使用搜索功能打开“地图”应用,在搜索中搜索某个地

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.