css样式
body, html { width: 100%; height: 100%; overflow: hidden; margin: 0; font-family: "微软雅黑"; } #allmap { width: 100%; height: 92%; position: relative; } .panel { position: absolute; padding: 20px; z-index: 9999; } #info { margin: 10px; }
HTML文档
<div class="panel"> <div class="demoTable lay_search"> <div class="layui-inline"><input type="text" class="layui-input lay_input1" placeholder="点击地图选择起点" id="start" autocomplete="off"></div> <div class="layui-input-inline"><select name="end" id="end" class="layui-input"></select></div> <button class="layui-btn lay_btn1" data-type="reload" id="search">查询</button> </div> </div> <div id="allmap"></div> <div id="info"></div>
百度地图API
//终点数据; var endData = [ {id: 0, name: '北京动物园', lng: 116.344478, lat: 39.948353}, {id: 1, name: '北京西站', lng: 116.330105, lat: 39.902538}, {id: 2, name: '海淀公园', lng: 116.302509, lat: 39.991484}, {id: 3, name: '北京大兴国际机场', lng: 116.426116, lat: 39.512641}, {id: 4, name: '北京天安门', lng: 116.404053, lat: 39.915046}, {id: 5, name: '中国国家博物馆', lng: 116.406568, lat: 39.911393} ]; var endHtml = ""; endHtml += " <option value=\"\">选择终点</option>"; for (var i = 0; i < endData.length; i++) { endHtml += " <option value=" + endData[i].id + ">" + endData[i].name + "</option>" } $("#end").html(endHtml); //百度地图API功能 var map = new BMap.Map("allmap"); map.centerAndZoom("北京市", 15); map.enableScrollWheelZoom(true); //单击地图获取起点位置; var geocoder = new BMap.Geocoder(); map.addEventListener("click", function (e) { geocoder.getLocation(e.point, function (rs) { $("#start").val(rs.address + "," + rs.point.lng + "," + rs.point.lat); }); }); //默认路线; getDis('北京天安门', '116.404053', '39.512641', '北京动物园', '116.344478', '39.948353'); //查询路线; $("#search").click(function () { var startv = $("#start").val(); var endv = $("#end").val(); if (startv == "") { alert("起点不能为空"); $("#start").focus(); return false; } if (endv == "") { alert("终点不能为空"); $("#send").focus(); return false; } var sname = startv.split(",")[0]; var lng1 = startv.split(",")[1]; var lat1 = startv.split(",")[2]; var ename = endData[endv].name; var lng2 = endData[endv].lng; var lat2 = endData[endv].lat; //获取线路; getDis(sname, lng1, lat1, ename, lng2, lat2); }) //获取距离和时间; function getDis(sname, lng1, lat1, ename, lng2, lat2) { map.clearOverlays(); var output = "起点:" + sname + "至 终点:" + ename + " 时间:"; var searchComplete = function (results) { if (transit.getStatus() != BMAP_STATUS_SUCCESS) { return; } var plan = results.getPlan(0); output += plan.getDuration(true) + "\n"; output += "总路程为:"; output += plan.getDistance(true) + "\n"; } var transit = new BMap.DrivingRoute(map, { renderOptions: {map: map}, onSearchComplete: searchComplete, onPolylinesSet: function () { $("#info").html(output); } }); var start = new BMap.Point(lng1, lat1); var end = new BMap.Point(lng2, lat2); transit.search(start, end); }
完整代码:https://download.csdn.net/download/weixin_41290949/23551344
lockdatav Done!