1. 程式人生 > >百度地圖 框出省市邊界

百度地圖 框出省市邊界

話不多說直接上程式碼:

一、建立地圖

建立地圖物件;設立中心點以及地圖級別。

 var map = new BMap.Map("container");
 map.centerAndZoom(new BMap.Point(116.403765, 39.914850), 12);

二、新增地圖事件

地圖事件:添加了滾輪縮放。

map.enableScrollWheelZoom(true)

三、獲取行政區域

建構函式Boundary;

get方法,獲取行政區域的邊界。

rs是獲取到的結果。

獲取到邊界的點陣列後,新增一個多邊形覆蓋物。

points為一系列點的陣列,系統自動展示points裡所有點。

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, //設定多邊形邊線線粗
strokeOpacity: 1, //設定多邊形邊線透明度0-1
StrokeStyle: "solid", //設定多邊形邊線樣式為實線或虛線,取值 solid 或 dashed
strokeColor: "#ff0000", //設定多邊形邊線顏色
fillColor: "#00ffff", //設定多邊形填充顏色
fillOpacity:0.01 //設定多邊形填充顏色透明度0-1 注:標紅的地放你們可以去掉看一下效果,自己體驗一下
}); //建立多邊形覆蓋物
map.addOverlay(ply); //新增覆蓋物
map.setViewport(ply.getPath());    //調整視野

 

四、圖片效果圖:

1.紅色部分直接複製的效果圖:

  

 2.改變紅色部分的程式碼或去掉的效果圖:              

fillColor: "#00ffff", //設定多邊形填充顏色  
fillOpacity:1 //設定多邊形填充顏色透明度
//注:將透明度修改成1的效果是白幕區變fillColor設定的顏色,去掉就是下面的效果

                      

 五、完整程式碼

 

<!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>
<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), 12);

map.enableScrollWheelZoom(true)
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, //設定多邊形邊線線粗
                       
                       strokeOpacity: 1, //設定多邊形邊線透明度0-1
                       StrokeStyle: "solid", //設定多邊形邊線樣式為實線或虛線,取值 solid 或 dashed

                       strokeColor: "#ff0000", //設定多邊形邊線顏色
                      
                                       }); //建立多邊形覆蓋物
            map.addOverlay(ply);  //新增覆蓋物
            map.setViewport(ply.getPath());    //調整視野         
        }                
    });   
}

</script>
</body>

</html>