摘要:以前教過大家如何自行獲取行政區域,或者自定義獲取一個區域的邊界值。今天來教大家直接調用百度地圖API1.3(目前最新版本)來獲取行政區域的邊界值。
--------------------------------------------------------------------------------------
一、建立地圖
創建地圖對象;設立中心點。
var map = new BMap.Map("container"); map.centerAndZoom(new BMap.Point(116.403765, 39.914850), 5);
二、添加地圖事件和控件
控件:魚骨控件我用了迷你型的;
地圖事件:添加了滾輪縮放。
map.addControl(new BMap.NavigationControl({type: BMAP_NAVIGATION_CONTROL_SMALL})); map.enableScrollWheelZoom();
三、獲取行政區域
構造函數Boundary;
get方法,獲取行政區域的邊界。
rs是獲取到的結果。
var bdary = new BMap.Boundary(); bdary.get(name, function(rs){ //獲取行政區域 //這里是用戶自己的函數。 });
四、添加覆蓋物
獲取到邊界的點數組后,添加一個多邊形覆蓋物。
var count = rs.boundaries.length; //行政區域的點有多少個 for(var i = 0; i < count; i++){ var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多邊形覆蓋物 map.addOverlay(ply); //添加覆蓋物 }
五、調整視野
points為一系列點的數組,系統自動展示points里所有點。
map.setViewport(points); //調整視野
效果圖:

全部源代碼:
<!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=utf-8" /> <title>獲取地區輪廓線</title> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"> </script> <style type="text/css"> body{font-size:13px;margin:10px} #container{width:800px;height:500px;border:1px solid gray} </style> </head> <body> <div id="container"></div> <br /> 輸入省、直轄市或縣名稱:<input type="text" id="districtName" style="width:80px" value="重慶市"> <input type="button" onclick="getBoundary()" value="獲取輪廓線"> <script type="text/javascript"> var map = new BMap.Map("container"); map.centerAndZoom(new BMap.Point(116.403765, 39.914850), 5); map.addControl(new BMap.NavigationControl({type: BMAP_NAVIGATION_CONTROL_SMALL})); map.enableScrollWheelZoom(); function getBoundary(){ var bdary = new BMap.Boundary(); var name = document.getElementById("districtName").value; bdary.get(name, function(rs){ //獲取行政區域 map.clearOverlays(); //清除地圖覆蓋物 var count = rs.boundaries.length; //行政區域的點有多少個 for(var i = 0; i < count; i++){ var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多邊形覆蓋物 map.addOverlay(ply); //添加覆蓋物 map.setViewport(ply.getPath()); //調整視野 } }); } </script> </body> </html>
相關文章:
《自行獲取區域經緯度的工具》
http://www.cnblogs.com/milkmap/archive/2012/02/23/2365064.html
