gpt4 book ai didi

javascript - 如何将坐标字符串转换为 LatLngBound 对象?

转载 作者:行者123 更新时间:2023-11-29 09:53:43 26 4
gpt4 key购买 nike

我有一个对应于矩形的字符串,如下所示:

((x1,y1),x2,y2))

我想将其转换为 LatLngBounds 对象,并通过以下方式绘制矩形:

myRectangle.setBounds(latLngBounds);

myRectangle.setMap(map);

最佳答案

这是一种有趣的字符串格式。我敢打赌你错过了一个括号,它真的看起来像这样:

((x1,y1),(x2,y2))

现在的问题是那些 x1 等值代表什么。出于讨论的目的,我假设顺序是:

((s,w),(n,e))

如果顺序不正确,应该很明显如何修复代码。

解析它的一种简单方法是先去除所有括号,为了安全起见,我们将同时去除所有空格。然后你剩下:

s,w,n,e

这很容易拆分成一个数组:

// Given a coordString in '((s,w),(n,e))' format,
// construct and return a LatLngBounds object
function boundsFromCoordString( coordString ) {
var c = coordString.replace( /[\s()]/g, '' ).split( ',' );
// c is [ 's', 'w', 'n', 'e' ] (with the actual numbers)
var sw = new google.maps.LatLng( +c[0], +c[1] ),
ne = new google.maps.LatLng( +c[2], +c[3] );

return new google.maps.LatLngBounds( sw, ne );
}

var testBounds = boundsFromCoorString( '((1.2,3.4),(5.6,7.8))' );

如果您不熟悉 +c[0] 等代码中 + 的用法,它会将字符串转换为数字。这很像使用 parseFloat()

我之前发布了一个更复杂的方法。我会把它留在这里,因为冗长的注释正则表达式可能很有趣:

var coordString = '((1.2,3.4),(5.6,7.8))';
var match = coordString
.replace( /\s/g, '' )
.match( /^\(\((.*),(.*)\),\((.*),(.*)\)\)$/ );
if( match ) {
var
s = +match[1],
w = +match[2],
n = +match[3],
e = +match[4],
sw = new google.maps.LatLng( s, w ),
ne = new google.maps.LatLng( n, e ),
bounds = new google.maps.LatLngBounds( sw, ne );
}
else {
// failed
}

.match() 调用中的正则表达式一团糟,不是吗?当正则表达式采用这种单行格式时,它们并不是最易读的语言。为清楚起见,让我们将其分成多行,就像您在 Python 或 Ruby 等语言中所做的那样:

.match( /               Start regular expression
^ Beginning of string
\( Initial open paren
\( Open paren for the first pair
(.*) First number
, Comma inside the first pair
(.*) Second number
\) Close paren for the first pair
, Comma separating the two pairs
\( Open paren for the second pair
(.*) Third number
, Comma inside the second pair
(.*) Fourth number
\) Close paren for the second pair
\) Final close paren
$ End of string
/ ); End regular expression

如果字符串中没有空格,可以省略这一行:

    .replace( /\s/g, '' )

为了简单起见,这只是在执行 .match() 之前删除空格。

关于javascript - 如何将坐标字符串转换为 LatLngBound 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16967835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com