外部文件的引入
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/> <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script> <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=ca11d9894383ee611ed5c6**&plugin=AMap.Driving"></script> <script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
构建地图容器和面板
<div id="container"></div> <div class="info" id="text"> <input type="text" id="start" placeholder="单击左键获取起点位置"> <input type="text" id="end" placeholder="单击右键获取终点位置"> <button id="btn">查询路线</button> </div> <div id="panel"></div>
起终点位置经纬度的驾车规划路线
//基本地图加载 var map = new AMap.Map("container", { resizeEnable: true, center: [121.548181, 29.806906], zoom: 13 }); //构造路线导航类 var driving = new AMap.Driving({ map: map, // panel: "panel" }); //默认路线; var start = '121.546266,29.80975'; var end = '121.549957,29.809508'; getGis(start, end); document.querySelector("#btn").onclick = function getLngLat() { var start1 = document.querySelector("#start").value; var end1 = document.querySelector("#end").value; getGis(start1, end1); } /* AMap.event.addListener(map, "click", function (e) { console.log(e) });*/ map.on("click", function (e) { var lnglat = e.lnglat.getLng() + "," + e.lnglat.getLat(); console.log(lnglat); document.querySelector("#start").value = lnglat; }); map.on("rightclick", function (e) { var lnglat = e.lnglat.getLng() + "," + e.lnglat.getLat(); console.log(lnglat); document.querySelector("#end").value = lnglat; }); //计算起始点的路线规划; function getGis(start, end) { var lng1 = start.split(',')[0]; var lat1 = start.split(',')[1]; var lng2 = end.split(',')[0]; var lat2 = end.split(',')[1]; // 根据起终点经纬度规划驾车导航路线 driving.search(new AMap.LngLat(lng1, lat1), new AMap.LngLat(lng2, lat2), function (status, result) { // result 即是对应的驾车导航信息 console.log(result.routes[0].distance + '米'); console.log(parseFloat(result.routes[0].time / 60).toFixed(2) + '分钟'); if (status === 'complete') { log.success('绘制驾车路线完成') } else { log.error('获取驾车数据失败:' + result) } }); }
lockdatav Done!