我想通过纬度和经度点数组创建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的字符串。第二个函数创建一个链接标签,该标签的href属性代表xml字符串,而download属性则包含download属性。附加链接,然后单击它以下载文件。