百度地圖api 自定義駕車線路規劃 車輛實時定位

初學者的淺談發表於2017-04-14

專案需求 根據百度api給出的介面 實現從 始發地→目的地 線路規劃 以及 車輛的實時位置跟蹤定位

1.首先引入百度API

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=g0EGHiZVlG52nvXSmZsozaQVERtS9dPh"></script>

2.HTML內容

<body>
<div id="allmap"></div>
</body>

3.在HTML外面具體邏輯

<script src="http://www.anfenglei.com/jds/JavaScript/jquer1.8.3.js"></script>
<script type="text/javascript">
    var coordinateArr = [] //定義一個全聚德所有的繪製線路點座標陣列
    var icona = []; //定義標註圖示陣列
    var zhandianpoint = []; //定義站點座標陣列
    var map = new BMap.Map("allmap");
    map.enableScrollWheelZoom(true); //可以縮放移動
    map.centerAndZoom(new BMap.Point(122.187499, 37.974944), 10);
    //新增縮略地圖控制元件
    //設定標註的圖示
    var icon1 = new BMap.Icon("image/shang.png", new BMap.Size(25, 33)); //上車點
    var icon2 = new BMap.Icon("image/xia.png", new BMap.Size(25, 33)); //下車點
    var icon3 = new BMap.Icon("image/tujing.png", new BMap.Size(25, 25)); //站點
    //var icon4 = new BMap.Icon("", new BMap.Size(25, 25)); //站點
    icona.push(icon1); //將圖示物件存入陣列
    icona.push(icon2); //將圖示物件存入陣列
    icona.push(icon3); //將圖示物件存入陣列
     //icona.push(icon4);
    $(document).ready(function() {
        //獲取站點資訊
        $.get("js/zhandianceshi.json", function(d) {

            $.each(d.data, function(idx, item) {
                //              if(idx == 0) {
                //                  return true; //同countinue,返回false同break
                //              }

                var lng_lat = this.geometry.coordinates; //獲取接送資料

                var point = new BMap.Point(lng_lat[0], lng_lat[1]); // 建立點
                zhandianpoint.push(point); //將所有點座標給陣列
                // 建立標註座標 設定所有點座標圖片 這個一定要在迴圈裡面
                 if(this.jiuzheng!==1){
                    var marker = new BMap.Marker(point, {
                    icon: icona[2]
                });
                map.addOverlay(marker); 

                var content = "<div style='overflow:hidden;width:300px;'>"; //設定標註資訊 這個也要在迴圈裡面這是寫的 上車下車
                content = content + "<p style='padding:0;margin:0 ;width:80%;border-radius:4px;margin:0 auto ;margin-bottom:10px;  border:1px solid #f90;overflow:hidden;'><span style='display: inline-block; width:40% ;line-height:30px ; color:green ;  text-align: center;  float: left;'>" + this.geometry.type + "</span><span style='display: inline-block; width:60% ; line-height:30px ; color:green ; text-align: center;  float: left;'>" + this.name + "</span></p>";
                content = content + "<div style=' width:50% ; float: left;overflow:hidden;'>";
                content = content + "<img src='" + this.image1 + "'style='width:140px;height:105px;'/>";
                content = content + "<span style='width:140px;display: inline-block;font-size:12px;'>" + this.title1 + "</span>";
                content = content + "</div>";
                content = content + "<div style=' width:50% ; float:right;overflow:hidden;'>";
                content = content + "<img src='" + this.image2 + "'style='width:140px;height:105px;'/>";
                content = content + "<span style='width:140px;display: inline-block;font-size:12px;'>" + this.title2 + "</span>";
                content = content + "</div>";
                content += "</div>";

                var infowindow = new BMap.InfoWindow(content);
                marker.addEventListener("click", function() {
                    this.openInfoWindow(infowindow);
                });
      //將標註新增到地圖 這個一定要在迴圈裡面
}



            });
            //alert(zhandianpoint.length)
            //上車點 下車點 一定要在迴圈外邊
            //設定第一個點的座標(上車點)圖片

            var marker1 = new BMap.Marker(zhandianpoint[0], {
                icon: icona[0]
            });
            //設定最後一個點的座標(下車點)圖片
            var marker2 = new BMap.Marker(zhandianpoint[zhandianpoint.length - 1], {
                icon: icona[1]
            });
//           var marker3 = new BMap.Marker(zhandianpoint[zhandianpoint.length - 2], {
//              icon: icona[0]
//          });
            //map.removeOverlay(marker3);
            map.addOverlay(marker1); //將標註新增到地圖
            map.addOverlay(marker2); //將標註新增到地圖
            //map.addOverlay(marker3);
//          marker3.addEventListener("click", function() {
//              //this.openInfoWindow(infowindow1);
//          });
            //map.removeOverlay(marker3);
            var content1 = "<div style='overflow:hidden; width:300px;'>"; //設定標註資訊 這個也要在迴圈裡面這是寫的 上車下車
            content1 = content1 + "<p style='padding:0;margin:0 ;width:80%;border-radius:4px;margin:0 auto ;margin-bottom:10px;  border:1px solid #f90;overflow:hidden;'><span style='display: inline-block; width:40% ;line-height:30px ; color:green ;  text-align: center;  float: left;'>" + d.data[0].geometry.type + "</span><span style='display: inline-block; width:60% ; line-height:30px ; color:green ; text-align: center;  float: left;'>" + d.data[0].name + "</span></p>";
            content1 = content1 + "<div style=' width:50% ; float: left;overflow:hidden;'>";
            content1 = content1 + "<img src='" + d.data[0].image1 + "'style='width:140px;height:105px;'/>";
            content1 = content1 + "<span style='width:140px;display: inline-block;font-size:12px;'>" + d.data[0].title1 + "</span>";
            content1 = content1 + "</div>";
            content1 = content1 + "<div style=' width:50% ; float:right;overflow:hidden;'>";
            content1 = content1 + "<img src='" + d.data[0].image2 + "'style='width:140px;height:105px;'/>";
            content1 = content1 + "<span style='width:140px;display: inline-block;font-size:12px;'>" + d.data[0].title2 + "</span>";
            content1 = content1 + "</div>";
            content1 += "</div>";
            var infowindow1 = new BMap.InfoWindow(content1);
            marker1.addEventListener("click", function() {
                this.openInfoWindow(infowindow1);
            });
                        if(d.data[d.data.length - 1].image1==""){

                            var content2 = "<div style='overflow:hidden;width:300px;'>"; //設定標註資訊 這個也要在迴圈裡面這是寫的 上車下車
            content2 = content2 + "<p style='padding:0;margin:0 ;width:80%;border-radius:4px;margin:0 auto ;margin-bottom:10px;  border:1px solid #f90;overflow:hidden;'><span style='display: inline-block; width:40% ;line-height:30px ; color:green ;  text-align: center;  float: left;'>" + d.data[d.data.length - 1].geometry.type + "</span><span style='display: inline-block; width:60% ; line-height:30px ; color:green ; text-align: center;  float: left;'>" + d.data[d.data.length - 1].name + "</span></p>";
            content2 = content2 + "<div style=' width:48% ; float: left;overflow:hidden;'>";

            content2 = content2 + "<span style='width:140px;display: inline-block;font-size:12px;'>" + d.data[d.data.length - 1].title1 + "</span>";
            content2 = content2 + "</div>";
            content2 = content2 + "<div style=' width:48% ; float:right;overflow:hidden;'>";

            content2 = content2 + "<span style='width:140px;display: inline-block;font-size:12px;'>" + d.data[d.data.length - 1].title2 + "</span>";
            content2 = content2 + "</div>";
            content2 += "</div>";
                        }else{
                            var content2 = "<div style='overflow:hidden;width:300px;'>"; //設定標註資訊 這個也要在迴圈裡面這是寫的 上車下車
            content2 = content2 + "<p style='padding:0;margin:0 ;width:80%;border-radius:4px;margin:0 auto ;margin-bottom:10px;  border:1px solid #f90;overflow:hidden;'><span style='display: inline-block; width:40% ;line-height:30px ; color:green ;  text-align: center;  float: left;'>" + d.data[d.data.length - 1].geometry.type + "</span><span style='display: inline-block; width:60% ; line-height:30px ; color:green ; text-align: center;  float: left;'>" + d.data[d.data.length - 1].name + "</span></p>";
            content2 = content2 + "<div style=' width:48% ; float: left;overflow:hidden;'>";
            content2 = content2 + "<img src='" + d.data[d.data.length - 1].image1 + "'style='width:140px;height:105px;'/>";
            content2 = content2 + "<span style='width:140px;display: inline-block;font-size:12px;'>" + d.data[d.data.length - 1].title1 + "</span>";
            content2 = content2 + "</div>";
            content2 = content2 + "<div style=' width:48% ; float:right;overflow:hidden;'>";
            content2 = content2 + "<img src='" + d.data[d.data.length - 1].image2 + "'style='width:140px;height:105px;'/>";
            content2 = content2 + "<span style='width:140px;display: inline-block;font-size:12px;'>" + d.data[d.data.length - 1].title2 + "</span>";
            content2 = content2 + "</div>";
            content2 += "</div>";
                        }

            var infowindow2 = new BMap.InfoWindow(content2);
            marker2.addEventListener("click", function() {
                this.openInfoWindow(infowindow2);
            });

            //  var p1 = zhandianpoint[0];//上車點
            //  var p2 = zhandianpoint[zhandianpoint.length - 1];//下車點
            //  var myP3 = zhandianpoint[1]; //途徑
            //  var myP4 = zhandianpoint[2]; //途徑
            //  var myP5 = zhandianpoint[3]; //途徑

            var driving = new BMap.DrivingRoute(map); //建立駕車例項
            var shugroup = Number((zhandianpoint.length) - 1)
                //alert(shugroup)
            for(var i = 0; i < shugroup; i++) {

                driving.search(zhandianpoint[i], zhandianpoint[i + 1]); //waypoints表示途經點
            }
            //  driving.search(p1, myP3); //第一個駕車搜尋  
            //  driving.search(myP3, myP4); //第一個駕車搜尋
            //  driving.search(myP4, myP5); //第一個駕車搜尋
            //  driving.search(myP5, p2); //第一個駕車搜尋

            driving.setSearchCompleteCallback(function() {
                var pts = driving.getResults().getPlan(0).getRoute(0).getPath(); //通過駕車例項,獲得一系列點的陣列

                var polyline = new BMap.Polyline(pts, {
                    strokeColor: "green", //顏色
                    strokeWeight: 4, //粗細
                    strokeOpacity: 0.6 //不透明度
                })

                map.addOverlay(polyline);

                map.setViewport(zhandianpoint);
                //map.setViewport(allPoints);

            });

        });

    });
</script>

4.zhandianceshi.json指令碼

{
“data”:[
{“id”:1,
“jiuzheng”:0,
“name”: “學校1”,
“image1”: “image/1-1.jpg”,
“image2”: “image/1-2.jpg”,
“title1”: “說明1”,
“title2”: “說明2”,
“geometry”:
{“type”: “上車點”, “coordinates”:[122.384485,36.101752]}
},
{“id”:2,
“jiuzheng”:0,
“name”: “學校2”,
“image1”: “image/2-1.jpg”,
“image2”: “image/2-2.jpg”,
“title1”: “說明1”,
“title2”: “說明2”,
“geometry”:
{“type”: “途徑站點”, “coordinates”:[122.374139,36.101374]}
},
{“id”:3,
“jiuzheng”:0,
“name”: “學校3”,
“image1”: “image/3-1.jpg”,
“image2”: “image/3-2.jpg”,
“title1”: “說明1”,
“title2”: “說明2”,
“geometry”:
{“type”: “途徑站點”, “coordinates”:[122.367837,36.10335]}
},
{“id”:4,
“jiuzheng”:1,
“name”: “糾正點”,
“image1”: “”,
“image2”: “”,
“title1”: “”,
“title2”: “”,
“geometry”:
{“type”: “途徑站點”, “coordinates”:[122.367855,36.10355]}
},
{“id”:5,
“jiuzheng”:0,
“name”: “終點”,
“image1”: “”,
“image2”: “”,
“title1”: “”,
“title2”: “”,
“geometry”:
{“type”: “下車點”, “coordinates”: [120.125554,36.314088]}
}
]

}

下面說說 車輛是如何定位的實現方法:

這兩個指令碼一定要載入地圖下邊 等地圖載入完成
1建立小車例項:new_carAction.js

 //車輛相關操作(必須放在地圖初始化完成之後載入)
 //----------------小車實體類(用於封裝小車常用操作)---------------------
 var carEntity = (function() {
     var lastTime;
     var carPosition; //小車位置
     var carLabel; //小車標註
     var car; //小車
     //建立小車(小車圖示,小車初始化經、緯度)
     var createCar = function(carIcon, lng, lat) {
         carPosition = new BMap.Point(lng, lat);
         car = new BMap.Marker(carPosition, {
             icon: carIcon
         });
         car.setTop(true);
         car.disableMassClear()
         return car;
     };
     //建立標註(標註顯示的資訊(標題+標註內容),標註相對小車偏移位置)
     var createLabel = function(carTitle, carContent, size1, size2) {
         carLabel = new BMap.Label(carContent, {
             offset: new BMap.Size(size1, size2)
         });
         carLabel.setTitle(carTitle);
         carLabel.disableMassClear();
         return carLabel;
     };
     //建立小車並設定標註
     var createCarAndSetLabel = function(carIcon, lng, lat, carTitle, carContent, size1, size2) {
         car = createCar(carIcon, lng, lat);
         car.setLabel(createLabel(carTitle, carContent, size1, size2));
         return car;
     };
     //更改小車座標及方向
     var changeCarPostion = function(lng, lat, rot) {
         if (carPosition) {
             carPosition.lng = lng;
             carPosition.lat = lat;
             car.setPosition(carPosition); //更新座標
             car.setRotation(rot); //修改方向
         }
     };
     //給小車繫結事件
     var addCarEvent = function(act, operation) {
         car.addEventListener(act, operation);
     };
     //刪除小車某個繫結事件
     var removeCarEvent = function(act, operation) {
         car.addEventListener(act, operation);
     };
     //public介面(對外開放的呼叫方法)
     return {
         getCar: function() {
             return car
         },
         getPosition: function() {
             return carPosition;
         },
         getLabel: function() {
             return carLabel;
         },
         getTime: function() {
             return lastTime;
         },
         setTime: function(nowTime) {
             lastTime = nowTime;
         },
         //建立標註
         newLabel: createLabel,
         //建立小車
         newCar: createCar,
         //建立車輛和標註(合成上面兩步)
         newCarAndSetLabel: createCarAndSetLabel,
         //改變車輛位置
         changePosition: changeCarPostion,
         //增加繫結事件
         addEvent: addCarEvent,
         //刪除繫結事件
         delEvent: removeCarEvent
     }
 });
 //--------------------彈出視窗資訊實體類-------------------
 var publicInfoWindowEntity = (function() {
     // 建立資訊視窗物件
     var publicInfoWindow = new BMap.InfoWindow("<div style='width:100%;height:100%'><h4 style='margin:0 0 5px 0;padding:0.2em 0' id='publicInfoWindowTitle'>車輛資訊</h4>" +
         "<img style='float:right;margin:1px' id='publicInfoWindowImg' src='/entbus/themes/default/image/che.png' width='12' height='22' title='車輛資訊'/>" +
         "<p>車牌號:<span id='publicInfoWindowCarNum'>" + 1 +
         "</span></p><p>位置:<span id='publicInfoWindowCarLng'>" + 2 +
         "</span>,<span id='publicInfoWindowCarLat'>" + 3 + "</span></p><p>定位時間:<span></span></p></div>");

     //改變公共彈出視窗
     function changePublicInfoWindow(witchCar, lastTime) {
         var carTitle = witchCar.getLabel().getTitle();
         var carPos = witchCar.getPosition();
         publicInfoWindow.setTitle(carTitle);
         publicInfoWindow.setContent("<div style='width:100%;height:100%'><h4 style='margin:0 0 5px 0;padding:0.2em 0' id='publicInfoWindowTitle'>車輛資訊</h4>" +
             "<img style='float:right;margin:1px' id='publicInfoWindowImg' src='/entbus/themes/default/image/che.png' width='12' height='25' title='車輛資訊'/>" +
             "<p>車牌號:<span id='publicInfoWindowCarNum'>" + carTitle +
             "</span></p><p>位置:<span id='publicInfoWindowCarLng'>" + carPos.lng +
             "</span>,<span id='publicInfoWindowCarLat'>" + carPos.lat + "</span></p><p>定位時間:<span></span>" + lastTime + "</p></div>");
     }
     return {
         //獲取當前視窗
         getInfoWindow: function() {
             return publicInfoWindow;
         },
         //改變視窗資訊
         changeInfo: changePublicInfoWindow
     }
 });

 //建立車輛公共圖示方法
 var createCarIcon = function(imgUrl, width, height, offset1, offset2) {
     return new BMap.Icon(imgUrl, new BMap.Size(width, height), { //小車圖片
         //offset: new BMap.Size(0, -5),    //相當於CSS精靈
         imageOffset: new BMap.Size(offset1, offset2) //圖片的偏移量。為了是圖片底部中心對準座標點。
     });
 };
 //建立公共的小車圖示所有小車都可以使用
 var myIcon = createCarIcon("/entbus/themes/default/image/che.png", 12, 25, 0, 0);

2.小車運動程式碼:new_demoAction.js

//例項演示
//用於演示車輛定位和電子圍欄功能

//建立一個小車操作物件
var car1 = new carEntity();
//建立小車例項
//car1.newCarAndSetLabel(myIcon, 120.399275,36.087634, "魯B1151", "魯B1151", 0, -15);
//把小車新增到地圖
//map.addOverlay(car1.newCarAndSetLabel(myIcon, 120.399275,36.087634, "魯B1151", "魯B1151", 0, -15));//可以這樣做
car1.newCar(myIcon)  //建立小車例項
map.addOverlay(car1.getCar());            //將小車新增到地圖
//car1.getCar().hide();
//顯示小車
function showCar() {
    car1.getCar().show();
}
//隱藏小車
function hideCar() {
    car1.getCar().hide();
}
//測試小車跑起來

function testRun(pid) {
      //獲取站點資訊
//  var  chedongpoint=[] //定義線路陣列
  var chedongpointlng = []//定義線路經度陣列
  var chedongpointlat = []//定義線路緯度陣列
  var chedongpointrot = []//定義線路旋轉角度陣列
  $.get("實時座標.json", function (d) {
      var gps_lng = 0
      var gps_lat = 0
      var gps_rot = 0
      var bd_lng
      var bd_lat
      var bd_rot
            $.each(d.data, function(idx, item) {
//              if(idx == 0) {
//                  return true; //同countinue,返回false同break
//              } 

            var lng_lat = this.coordinates; //獲取json資料
          var point = new BMap.Point(lng_lat[0],lng_lat[1]);
                var pointlng =lng_lat[0]; // 建立經度點
                var pointlat = lng_lat[1]; // 建立緯度點
                var pointrot = lng_lat[2]; // 建立小車偏移量


                gps_lng = lng_lat[0]; // 建立經度點
                gps_lat = lng_lat[1]; // 建立緯度點
                gps_rot = lng_lat[2]; // 建立小車偏移量

                //chedongpoint.push(point);
                chedongpointlng.push(pointlng); //將經度點傳陣列
                chedongpointlat.push(pointlat);//將緯度點傳陣列
                chedongpointrot.push(pointrot);//將小車偏移量傳陣列

            });


            var gpsPoint = new BMap.Point(gps_lng, gps_lat);
            translateCallback = function (pointa) {
                bd_lng = pointa.lng
                bd_lat = pointa.lat
                bd_rot = gps_rot;
                // alert(pointa.lng + "," + pointa.lat);
            }
            BMap.Convertor.translate(gpsPoint, 0, translateCallback);     //真實經緯度轉成百度座標

                //alert(chedongpoint.length)

            setTimeout(function () {
                car1.changePosition(bd_lng, bd_lat, bd_rot); // 小車的動態位置

            }, 1000);

            });

如有使用請換上 自己的 座標點 即可
因為第一次寫 有什麼不足請指教
詳情QQ:1140376389

相關文章