我正在尝试使用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 ....等,以便我有:
号码,号码,号码,........
荒谬地,每个奇怪的麻木逗号。现在它出于某种原因删除了所有逗号。
答案 0 :(得分:1)
最简单的解决方案(?) - 添加另一个坐标(以 it' s 逗号开头),使其成为一对,单独捕获不带逗号:
([^,]+[^,]),([^,]+[^,],)
替换为
$1 $2
(空格和尾随之间)
重构坐标对,不使用分隔逗号,而是留下尾随。
答案 1 :(得分:1)
看起来coords
是Leaflet's LatLng
s的数组。考虑到您可以使用toString()
和.lat
来访问.lng
的属性,使用LatLng
是一件很奇怪的事情。
由于您使用空格和逗号,您似乎也在尝试将数据转换为WKT(Well-Known-Text)。
因此,您可以使用以下内容将LatLng
转换为WKT坐标对:
var latlng = L.latLng(...)
var wktPoint = latlng.lng + ' ' + latlng.lat;
而且,如果您有LatLng
个数组,则可以在此处使用Array.prototype.map
和Array.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()
等来更好地控制输出。