从点创建一个 GPX 文件并使用 javascript 下载它

Create a GPX file from points and download it using javascript

我想从一组纬度和经度点创建一个 gpx 文件。 我的阵列看起来像这样:

const lineSegments = [[[34.12877, -117.65464], [34.12878, -117.65391]], ....];

我想变成这样的 gpx 文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<gpx version="1.1" creator="https://mywebsite.com" xmlns="http://www.topografix.com/GPX/1/1">
  <metadata>
    <name>0.62 mi route</name>
    <link href="https://mywebsite.com">
      <text>My Website</text>
    </link>
    <time>2020-04-22T20:10:34.445Z</time>
    <copyright author="My Web Site, OpenStreetMap Contributors">
      <year>2020</year>
    </copyright>
  </metadata>
  <rte>
    <name>0.62 mi route</name>
    <rtept lat="34.12877" lon="-117.65464"/>
    <rtept lat="34.12878" lon="-117.65391"/>
    <rtept lat="34.12878" lon="-117.65368"/>
    <rtept lat="34.12878" lon="-117.6531"/>
    <rtept lat="34.12878" lon="-117.65231"/>
    <rtept lat="34.12878" lon="-117.65142"/>
    <rtept lat="34.12879" lon="-117.65127"/>
    <rtept lat="34.12879" lon="-117.65111"/>
    <rtept lat="34.12879" lon="-117.65045"/>
    <rtept lat="34.12879" lon="-117.64991"/>
    <rtept lat="34.12879" lon="-117.6493"/>
    <rtept lat="34.12879" lon="-117.64872"/>
    <rtept lat="34.1288" lon="-117.64816"/>
    <rtept lat="34.1288" lon="-117.64758"/>
    <rtept lat="34.1288" lon="-117.64583"/>
    <rtept lat="34.1288" lon="-117.64514"/>
    <rtept lat="34.1288" lon="-117.64485"/>
    <rtept lat="34.12879" lon="-117.64477"/>
    <rtept lat="34.12879" lon="-117.64411"/>
    <rtept lat="34.1286" lon="-117.64411"/>
  </rte>
</gpx>

我不太确定如何编写 .gpx 文件。有什么建议吗?

我的解决方案:

const createXmlString = (lines: number[][][]): string => {
  let result = '<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="runtracker"><metadata/><trk><name></name><desc></desc>'
  result += lines.reduce((accum, curr) => {
    let segmentTag = '<trkseg>';
    segmentTag += curr.map((point) => `<trkpt lat="${point[1]}" lon="${point[0]}"><ele>${point[2]}</ele></trkpt>`).join('');
    segmentTag += '</trkseg>'

    return accum += segmentTag;
  }, '');
  result += '</trk></gpx>';
  return result;
}

const downloadGpxFile = (
  lines: number[][][],
  distance: number[],
  units: 'miles' | 'kilometers'
) => {
  const xml = createXmlString(lines);
  const url = 'data:text/json;charset=utf-8,' + xml;
  const link = document.createElement('a');
  link.download = `${distance[distance.length - 1]}-${units}.gpx`;
  link.href = url;
  document.body.appendChild(link);
  link.click();
};

第一个函数通过遍历每行并为行中的每个点创建标签来创建一个表示 xml 的字符串。第二个函数创建一个 link 标签,其中包含一个代表 xml 字符串的 href 属性 和一个下载 属性。附加 link 并单击它以下载文件。