【问题标题】:Is this done with a regular expression? Formatting Latitude Longitude这是用正则表达式完成的吗?格式化纬度经度
【发布时间】:2017-07-07 15:27:49
【问题描述】:

我正在尝试使用 Leaflet Draw 格式化一个多边形(几个连接在一起的纬度/经度坐标)。这是格式返回和我到目前为止所做的:

map.on("draw:drawstop", polyPointToString);              
function polyPointToString(e){
    console.log("Unaltered Coordinates: " + coords);
    polyStringParse = coords.toString().replace(/[^\d,.-]/g, '');             
    console.log("Polyparse: " + polyStringParse);
    polyStringParseRegExp = polyStringParse.replace(/([^,]+[^,]),/g,'$1 ');
    console.log("PolyparseRegExp: " + polyStringParseRegExp);
}

原坐标是这样的:

//Unaltered Coordinates: LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414),LatLng(46.58907, -102.74414)

PolyParse 是这样的(只剩下数字、破折号和小数点):

//Polyparse: 46.58907,-102.74414,46.58907,-102.74414,46.58907,-102.74414

PolyparseRegExpt 是这个(它不断删除所有逗号:-():

//Polyparse2: 46.58907 -102.74414 46.58907 -102.74414 46.58907 -102.74414

需要什么:逗号 1、3、5、7.... 等已删除,以便我拥有:

号码号码,号码号码,号码号码,........

基本上,每个奇怪的麻木逗号。现在由于某种原因它正在删除所有逗号。

【问题讨论】:

  • coords 是什么,不是作为字符串,而是作为对象?将您的 console.log 更改为 console.log("Unaltered Coordinates: ", coords)。将对象转换为字符串表示形式,然后将其解析出来会使这变得不必要地复杂。
  • coords 是地图上的点数组。
  • 我认真地认为您使用正则表达式格式化此数组的方法是the XY problem

标签: javascript regex leaflet


【解决方案1】:

最简单的解决方案 (?) - 添加另一个坐标(前面是 它的 逗号),使其成为一对,分别捕获它没有逗号:

([^,]+[^,]),([^,]+[^,],)

替换为

$1 $2(和尾随空格)

重整坐标对,不使用逗号分隔,但保留尾随。

See it here at regex101.

【讨论】:

  • 嘿ClasG。谢谢,但这似乎正在删除偶数逗号。我需要第一,第三,第五,..等等。Regex101 看起来很酷。不知道存在。
  • 很抱歉。读得很草率;)已修复。
  • 太棒了! RegEx 对我来说仍然有点神秘(昨天才知道它的存在)。我非常感谢您的帮助。
  • 很高兴为您提供帮助。请标记为已接受的答案(很重要,因为它让有类似问题的人更容易找到),如果你觉得它有用 - 点赞;)
【解决方案2】:

看起来coordsLeaflet's LatLngs 的数组。考虑到您可以使用.lat.lng 访问LatLng 的属性,使用toString() 是一件奇怪的事情。

由于您使用了空格和逗号,您似乎也在尝试将数据转换为 WKT(众所周知的文本)。

因此,您可以将 LatLng 转换为 WKT 坐标对,如下所示:

var latlng = L.latLng(...)
var wktPoint = latlng.lng + ' ' + latlng.lat;

而且,如果你有一个 LatLngs 数组,你可以在这里使用 Array.prototype.mapArray.prototype.join 来获得很好的效果:

var coords = [ L.latLng(...), L.latLng(...), ... ];

var wktLineString = coords.map(function(ll){
    // For every item in the array, return a string.
    // The call to .map() will thus return an array of strings
    return ll.lng + ' ' + ll.lat;

    // Once the array of strings is ready, join those strings
    // with the given separator.
}).join(',');

假设您使用的是 WKT,请注意坐标的交换,以便您可以使用 lng-lat 而不是 lat-lng。另请注意,您可以使用toFixed() 等来更好地控制输出。

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 2011-03-31
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多