我有一个字符串对应于一个矩形,如下所示:
((x1,y1),x2,y2))
我希望将其转换为LatLngBounds对象,并通过以下方式绘制矩形:
myRectangle.setBounds(latLngBounds);
或者
myRectangle.setMap(map);
我有一个字符串对应于一个矩形,如下所示:
((x1,y1),x2,y2))
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()
之前移除空格。