【百度地图API】如何进行地址解析与反地址解析?——模糊地址能搜索到精确地理信息!

摘要:

  什么是地址解析?

  什么是反地址解析?

  如何运用地址解析,和反地址解析?

  可以同时运用地址解析,和反地址解析麼?答案是,可以的。详见最后一个示例与代码。

---------------------------------------------------------------------------------

一、地址解析

地址解析,是用户输入一个详细到门牌号的地址。例如“北京市中关村南大街27号中央民族大学”,那么地址解析接口,会返回一个经纬度Point。

接口定义如下:

getPoint(address:String, callback:Function, city:String)

对指定的地址进行解析。如果地址定位成功,则以地址所在的坐标点Point为参数调用回调函数。否则,回调函数的参数为nullcity为地址所在的城市名,例如“北京市”。

代码示例:

// 创建地址解析器实例
var myGeo = new BMap.Geocoder();
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint("北京市海淀区上地10街", function(point){
if (point) {
map.centerAndZoom(point,
16);
map.addOverlay(
new BMap.Marker(point));
}
},
"北京市");

运行该示例,请点击:http://openapi.baidu.com/map/examples.html?v=1.1&7_12#7&12 

二、反地址解析

反地址解析,就是传进去一个经纬度Point,它会返回一个详细的地址。具体地址有多详细,就要看百度数据库里的数据了。

接口定义如下:

getLocation(point:Point, callback:function[, options:LocationOptions])

对指定的坐标点进行反向地址解析。如果解析成功,则回调函数的参数为GeocoderResult对象,否则回调函数的参数为null

代码示例:

var gc = new BMap.Geocoder();

map.addEventListener(
"click", function(e){
var pt = e.point;
gc.getLocation(pt,
function(rs){
var addComp = rs.addressComponents;
alert(addComp.province
+ ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
});
});

运行该示例,请点击:http://openapi.baidu.com/map/examples.html?v=1.1&7_15#7&15

三、同时运用地址解析与反地址解析

在什么情况下需要同时运用这两个接口呢?

答案是,当你搜索一个模糊的地址,但却想要返回一个精确的地址结果。

例如“上海市新华路”,但是你想知道“新华路”在哪个区县的时候,你就可以同时利用这两个接口。

完整HTML代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>地址解析+反地址解析</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
</head>
<body>
<div style="width:520px;height:340px;border:1px solid gray" id="container"></div>
<div style="margin:10px 0;"><input type="text" style="width:300px;margin-right:10px;" value="新华路" id="searchValue" /><input type="button" value="搜索" onclick="search()" /></div>

</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("container");
map.centerAndZoom(
new BMap.Point(121.461165,31.234095), 11);
function search(){
var myAddress = document.getElementById('searchValue').value;

var myGeo = new BMap.Geocoder();
myGeo.getPoint(myAddress,
function(point){ //我输入的是“知春路”,第一步getPoint是地址解析。
if (point) {
map.centerAndZoom(point,
16);
map.addOverlay(
new BMap.Marker(point));

myGeo.getLocation(point,
function(rs){ //这里弹出“知春路”的详细地址信息,第二步getLocation是反地址解析。
var addComp = rs.addressComponents;
alert(myAddress
+'的具体位置是:'+addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
});
}
},
"上海市"); //必须设置城市

}
</script>

地址解析+反地址解析示例说明:

1、运行以上HTML代码,会出现这样一个输入框,默认是新华路。点击搜索按钮。

2、经过了地址解析,与反地址解析后,得到了新华路所在地区的详细地址!!!

3、把得到的坐标标注出来。

posted @ 2011-05-27 13:50  酸奶小妹  阅读(40993)  评论(9编辑  收藏  举报