我们写的路径规划,是根据用户点击中国地图的次数为准的,进入页面,鼠标点击一次,就是需要规划的起点。点击第二次,就是终点,当点击完两次后,路径规划自动执行。
下面是详细代码,只需改变代码中key与密钥的值,改变成自己请求的值即可
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <title>地图路线规划练习 </title> <style type="text/css"> html, body, #container { width: 100%; height: 100%; } </style> <script type="text/javascript"> window._AMapSecurityConfig = { securityJsCode: "e39d93c48089b8b29f875697d91ec9ef", }; </script> <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://cache.amap.com/lbs/static/addToolbar.js"></script> <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=cfdc2e6bff151fb0402a7ceb4190834a&plugin=AMap.Driving"></script> </head> <body> <div id="container"></div> <div class="input-card"> <h4>设置起点和终点:</h4> <div class="input-item"> <input type="text" readonly="true" id="startPoint" placeholder="点击设置起点"> </div> <div class="input-item"> <input type="text" readonly="true" id="endPoint" placeholder="点击设置终点"> </div> </div> <script type="text/javascript"> var map = new AMap.Map("container", { resizeEnable: true, center: [113.94213,35.291235], zoom: 15 }); var startPoint; // 起点 var endPoint; // 终点 var Clicks = 0; // 点击次数 // AMap.Driving 类创建一个驾车路线规划对象给他赋值给driving并与名为map的地图对象关联 var driving = new AMap.Driving({ map: map }); map.on('click', function(e) { Clicks++; // 声明变量为0,点击一次现在是1,一取余三等于1,设置起点 if (Clicks % 3 === 1) { // 设置起点 startPoint = e.lnglat; document.getElementById("startPoint").value = "起点 - 经度: " + startPoint.getLng() + ", 纬度: " + startPoint.getLat(); console.log(startPoint); var marker = new AMap.Marker({ position: startPoint }); console.log(marker); marker.setMap(map); // 点击第二次现在是2,2取余三等于2,设置为终点点 } else if (Clicks % 3 === 2) { // 设置终点 endPoint = e.lnglat; document.getElementById("endPoint").value = "终点 - 经度: " + endPoint.getLng() + ", 纬度: " + endPoint .getLat(); var marker = new AMap.Marker({ position: endPoint }); marker.setMap(map); // 使用选定的点开始路线搜索 driving.search(startPoint, endPoint, function(status, result) { if (status === 'complete') { console.log('绘制驾车路线完成'); map.setCenter([startPoint.getLng(), startPoint.getLat()]); // 将地图中心设为起点 } else { console.error('获取驾车数据失败:' + result); } }); } else { // 起点清空 startPoint = null; // 终点清空 endPoint = null; // 起点了路径值清空 document.getElementById("startPoint").value = ""; // 终点了路径值清空 document.getElementById("endPoint").value = ""; // 点击的次数清零 Clicks = 0; map.clearMap(); } }); </script> </body> </html>