使用Geocoder進行地址解析,好比「北京市海淀區上地10街」,當系統匹配到這個地址時,getPoint就會返回一個座標點。
這裏須要用到回調函數。
var
myGeo
=
new
BMap.Geocoder();
//
將地址解析結果顯示在地圖上,並調整地圖視野
myGeo.getPoint(
"
北京市海淀區上地10街
"
,
function
(point){
if
(point) {
map.centerAndZoom(point,
16
);
map.addOverlay(
new
BMap.Marker(point));
}},
"
北京市
"
);
當系統沒法匹配「北京市海淀區上地10街」的時候,會返回「北京市海淀區」的幾何中心點。
若是仍是沒法匹配,會返回「北京市」的幾何中心點。
若是你只是想返回「北京市」的座標,或者說想要模糊查詢,建議不要使用地址解析。
而是使用LocalSearch類的search方法。例子詳見:
http:
//
www.cnblogs.com/milkmap/archive/2010/12/22/1914106.html
<!
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
>
<
html
>
<
head
>
<
title
>
地址解析失敗時搜索
</
title
>
<
meta
name
="Generator"
content
="EditPlus"
>
<
meta
name
="Author"
content
=""
>
<
meta
name
="Keywords"
content
=""
>
<
meta
name
="Description"
content
=""
>
<
script
type
="text/javascript"
src
="http://api.map.baidu.com/api?v=1.2"
></
script
>
</
head
>
<
body
>
<
div
id
="divMap"
style
="width:400px;height:400px;border:solid 1px gray"
></
div
>
<
script
type
="text/javascript"
>
var
map
=
new
BMap.Map(
"
divMap
"
);
map.centerAndZoom(
new
BMap.Point(
108.532769
,
22.825487
),
12
);
//
這裏是定義到了南寧市
var
gc
=
new
BMap.Geocoder();
gc.getPoint(
"
南寧市青秀區
"
,
function
(pt){
if
(pt){
map.addOverlay(
new
BMap.Marker(pt));
//
若是地址解析成功,則添加紅色marker
}
else
{
var
ls
=
new
BMap.LocalSearch(
"
南寧市
"
);
ls.search(
"
南寧市青秀區
"
);
ls.setSearchCompleteCallback(
function
(rs){
if
(ls.getStatus()
==
BMAP_STATUS_SUCCESS){
var
poi
=
rs.getPoi(
0
);
//
取第1個查詢結果
if
(poi){
var
pt2
=
poi.point;
map.addOverlay(
new
BMap.Marker(pt2));
//
若是查詢到,則添加紅色marker
}
}
else
{
alert(
"
fail
"
);
}
});
}
},
"
南寧市
"
);
</
script
>
</
body
>
</
html
>