我有一个矩形对应的字符串,像这样:
((x1,y1),x2,y2))
我想把它转换成一个latlnbounds对象,并绘制矩形:
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()
之前删除空白。
您需要使用LatLng创建西南角和东北角。然后你把这些传递给latlnbounds。