前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >点连线的思路与js的简单实现

点连线的思路与js的简单实现

作者头像
lzugis
发布2021-03-20 14:20:17
1.7K0
发布2021-03-20 14:20:17
举报

概述

很多时候,我们会有一堆点连成线的需求,但大多数情况下这些点是无序的,导致现有的软件的连线结果并不是我们想要的,这也是本文产生的原因。

实现思路

为了能够更好地完成点连成线的需求,因此我们需要确定一下起点,完了之后通过起点去逐个点找该点的下一个点,并将该点的坐标记录下来,直到找到终点,这个查找结束。

实现结果

QGIS软件实现
QGIS软件实现
arcgis软件实现
arcgis软件实现
代码实现
代码实现

实现代码

代码语言:javascript
复制
function Points2Line(start, data) {
    if (!this instanceof Points2Line) {
        return new Points2Line(start, res);
    }

    let len = data.length;
    let donePointIds = [start.properties.id];
    /**
     * 计算两点距离
     * @param coord1
     * @param coord2
     * @returns {number}
     */
    const getDistance = function (coord1, coord2) {
        const x = coord1[0] - coord2[0];
        const y = coord1[1] - coord2[1];
        return Math.sqrt(x * x + y * y);
    }
    /**
     * 获取最近点
     * @param point
     * @returns {object}
     */
    const getClosestPoint = function (point) {
        let dis = 999999;
        let index = 0
        for (let i = 0; i < len; i++) {
            const r = data[i];
            const coord = r.geometry.coordinates;
            if(donePointIds.indexOf(r.properties.id) === -1) {
                const _dis = getDistance(coord, point);
                if(dis > _dis ) {
                    index = i;
                    dis = _dis;
                }
            }
        }
        return data[index]
    }
    /**
     * 获取结果
     * @returns {{geometry: {coordinates: [*], type: string}, type: string, properties: {}}}
     */
    this.getResultGeojson = function () {
        let startCoord = start.geometry.coordinates;
        let coords = [startCoord];
        for (let i = 0; i < len - 1; i++) {
            const pt = getClosestPoint(startCoord)
            donePointIds.push(pt.properties.id)
            startCoord = pt.geometry.coordinates;
            coords.push(startCoord)
        }
        return {
            "type":"Feature",
            "properties":{},
            "geometry":{
            "type":"LineString",
                "coordinates": coords
            }
        }
    }
}

$.get('data/test.json', function (res) {
    res = res.features
    const startPoint = { "type": "Feature", "properties": { "id": 385 }, "geometry": { "type": "Point", "coordinates": [ 113.332675, 23.247206 ] } };
    const pt2line = new Points2Line(startPoint, res);
    console.log(JSON.stringify(pt2line.getResultGeojson()));
})

待优化:

  1. 本文中的起点是手动传入的,后需会增加自动获取起点的实现;
  2. 本文只实现了单条线,后续会增减多线的实现;
  3. 本文是通过js实现的,后面会增加java的实现。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-03-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 实现思路
  • 实现结果
  • 实现代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档