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

Ber*_*aud 3 javascript google-maps-api-3

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

((x1,y1),x2,y2))
Run Code Online (Sandbox Code Playgroud)

我想在LatLngBounds对象中转换它,并通过以下方式绘制矩形:

myRectangle.setBounds(latLngBounds);
Run Code Online (Sandbox Code Playgroud)

要么

myRectangle.setMap(map);
Run Code Online (Sandbox Code Playgroud)

Mic*_*ary 6

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

((x1,y1),(x2,y2))
Run Code Online (Sandbox Code Playgroud)

现在的问题是那些x1等值代表什么.出于讨论的目的,我将假设订单是:

((s,w),(n,e))
Run Code Online (Sandbox Code Playgroud)

如果这不是正确的顺序,应该很明显如何修复代码.

解析这个的一个简单方法是首先去除所有括号,为了安全起见,我们将同时删除任何空格.然后你离开了:

s,w,n,e
Run Code Online (Sandbox Code Playgroud)

这很容易分成一个数组:

// 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))' );
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉+代码中的使用+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
}
Run Code Online (Sandbox Code Playgroud)

.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
Run Code Online (Sandbox Code Playgroud)

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

    .replace( /\s/g, '' )
Run Code Online (Sandbox Code Playgroud)

这只是.match()为了简单起见之前删除空格.