我有一个对应于矩形的字符串,如下所示:
((x1,y1),x2,y2))
我想在LatLngBounds对象中转换它,并通过以下方式绘制矩形:
myRectangle.setBounds(latLngBounds);
或
myRectangle.setMap(map);
答案 0 :(得分:6)
这是一种有趣的字符串格式。我敢打赌你错过了一个括号,看起来真的像这样:
((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()
之前删除空格。
答案 1 :(得分:-1)
您需要使用LatLng创建SouthWest和NorthEast角落。然后你将它们传递给LatLngBounds。文档非常详尽。