如何将坐标字符串转换为latlnbound对象
How to convert a string of coordinate to a LatLngBound object?
我有一个矩形对应的字符串,像这样:
((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。
相关文章:
- 引用对象中的通用值
- jQuery匹配JSON对象的部分文本
- 节点导出返回一个空对象
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 全局变量和全局对象的属性之间有什么区别吗
- 比较从函数和生成的日期对象
- Javascript,访问一个主要对象模块模式中的每个对象
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 调整窗口大小时,可拖动的对象会出现在容器外部
- 如何使用javascript从主svg对象动态创建svg视图框
- 如何使用json将对象列表从java转换为javascript
- 序列化数据属性中对象的最可靠方法
- 如何访问声音管理器2创建的声音对象
- FabricJs-限制主对象内添加对象的移动区域
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 值对象在某个变量发生更改后发生更改
- 如何为json对象中的段发送array[]
- 如何将坐标字符串转换为latlnbound对象