任務描述:
酸奶小妹放寒假啦,要從北京呼啦一下飛回重慶呢。現在百度地圖API上不能直接切換城市,怎麼辦呢?
如何實作:
利用API先搜尋到要去城市,然後再讓搜尋到的城市顯示在地圖中心點。
(百度地圖上的實作方式是,給後端一個請求,後端傳回該城市的經緯度)
圖示:

代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<meta name="keywords" content="百度地圖,百度地圖API,百度地圖自定義工具,百度地圖所見即所得工具"/>
<meta name="description" content="百度地圖API自定義地圖,幫助使用者在可視化操作下生成百度地圖"/>
<title>從北京到重慶</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?&v=1.2">
</script>
</head>
<body>
<p>我要去<input id="txtSearch" type="text" value="重慶"/><input type="button" value="GO" onclick="search()"/></p>
<div style="width:520px;height:340px;border:1px solid gray;" id="container"></div>
</body>
<script type="text/javascript">
function $(id){
return document.getElementById(id); //定義$
}
var map =new BMap.Map("container"); //建立地圖
map.centerAndZoom(new BMap.Point(116.330599, 39.95536), 10); //初始化地圖
var city =new BMap.LocalSearch(map,{renderOptions:{map:map,autoViewport:true}}); //地圖顯示到查詢結果處
function search(){
var s = $("txtSearch").value;
city.search(s); //查找城市
</html>
2012-02-07 更新一下API1.2的代碼:
原理:localsearch關鍵詞,比如“西單”。
在回調函數裡,擷取第一個POI的經緯度,并且該點為中心點。