高德地图API使用

末鹿安然 提交于 2020-02-07 12:16:30

   高德地图二次开发提供了很多接口,功能强大。

   首先需要申请一个KEY教程如下:链接

   

  通过这个key替换

<script src="https://webapi.amap.com/maps?v=1.4.15&key=自己的KEY&plugin=AMap.Autocomplete"></script>

 其中plugin=AMap.Autocomplete为需要加载的组件类型,例如还有plugin=AMap.Driving等

 实现功能如下功能:

 可以在轨迹上查点,然后通过查询API导航轨迹:

 代码实现如下:

<!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>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <script type="text/javascript" src="./TrackEdit.js"></script>
    <script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>

</head>
<style type="text/css">
    html,body{
        width: 100%;
        height: 100%;
        margin: 0px;
    }
    .map{
        height: 100%;
        width: 100%;
        float: left;
    }
</style>
<body>
<div id="container" class="map"></div>
<div class="input-card">
    <h4>左击获取经纬度:</h4>
    <div class="input-item">
      <input type="text" readonly="true" id="lnglat">
    </div>
    <div>
        <button class="btn" id="add-node">新增节点</button>
        <button class="btn" id="remove-all">清除</button>
    </div>
    <div id="panel"></div>
</div>

<script src="https://webapi.amap.com/maps?v=1.4.15&key=自定义KEY&plugin=AMap.Autocomplete"></script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=自定义KEY&plugin=AMap.Driving"></script>
<script type="text/javascript">
	// 创建AMap对象
    var map = new AMap.Map("container", {
        resizeEnable: true,
        conter:[112.881898, 28.227956],
        rotateEnable:true,
        pitchEnable:true,
        zoom: 17,
        pitch:80,
       // rotation:-15,
       // viewMode:'3D',//开启3D视图,默认为关闭
        buildingAnimation:true,//楼块出现是否带动画
        expandZoomRange:true,
        zooms:[3,20],
    });
    map.setMapStyle("amap://styles/graffiti");

    //构造路线导航类
    var driving = new AMap.Driving({
        map: map,
        hideMarkers: true
    }); 
    
    //为地图注册click事件获取鼠标点击出的经纬度坐标
    var create = false;
    map.on('click', function(e) {
        document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat();
        if (create)
        {
          addNode(e.lnglat.getLng(), e.lnglat.getLat());
        }
    });
	
    var array_nodes = new Array();
    var array_line = new Array();
    var array_pos = new Array();
	
	// 增加一个节点
	function addNode(lng, lat)
	{
		var marker = new AMap.Marker({
        icon: "./rick.png",
        position: [lng, lat],
        draggable: true
        });

       var id = marker.getId();

       marker.on('dragging', moveNode);
       marker.on('mouseup', clickUP);
       array_nodes.push(marker);
       array_pos.push([lng, lat]);
       map.add(marker);

        if (array_nodes.length > 1)
        {
            drawLine(
            array_pos[array_pos.length - 1][0],
            array_pos[array_pos.length - 1][1],
            lng,
            lat
            );
        }
    }
    
    // 画线
    function drawLine(start_ln, start_lg, end_ln, end_lg)
    {
    //  array_line.push( new AMap.Polyline({
	//		path:[[start_ln, start_lg],[end_ln, end_lg]],
	//		strokeColor:'purple',
	//		lineCap:'round',
	//		isOutline:true,
	//		outlineColor:'',
	//		showDir:true,
	//		map:map,
	//		strokeWeight:5,
	//		borderWeight:2,
	//		strokeOpacity:0.5
    //  }));
        queryPlain();
    }

    // 更新线
    function updateLine(index)
    {
        var i = index - 1;
        var lat = array_nodes[index].Ke.position.getLat();
        var lng = array_nodes[index].Ke.position.getLng();
        if (i >= 0 && i < array_line.length)
        {
            var c = array_line[i].Ke;
            var start_ln = c.path[0].lat;
            var start_lg = c.path[0].lng;

            var line = [[start_ln, start_lg],[lat, lng]];
            map.remove(array_line[i]);
            array_line[i] = new AMap.Polyline({
			path:[[start_ln, start_lg],[lat, lng]],
			strokeColor:'purple',
			lineCap:'round',
			isOutline:true,
			outlineColor:'',
			showDir:true,
			map:map,
			strokeWeight:5,
			borderWeight:2,
			strokeOpacity:0.5
            })
            map.add(line);
           // array_line[i].setPath([[start_ln, start_lg],[lat, lng]]);
        
        }
        i = index;
        if (i < array_line.length)
        {
            var c = array_line[i].Ke;
            var end_lat = c.path[1].lat;
            var end_lng = c.path[1].lng;

            array_line[i].path = [[lat, lng],[end_lat, end_lng]];
            //array_line[i].setPath([[lat, lng],[end_lat, end_lng]]);
        }
    }

    // 移动
    function moveNode(e)
    {

    }

    function clickUP(e)
    {
        var exist = false;
        for (var i = 0; i < array_nodes.length; i++)
        {
            if (e.target.xga == array_nodes[i].getId())
            {
                exist = true;
                break;
            }
        }

        // 如果查找到,更新前后节点
        if (exist)
        {
            updateLine(i);
        }
    }
    

	document.querySelector("#remove-all").onclick = function() 
    {
        for (var i = 0; i < array_nodes.length; i++) {  
            map.remove(array_nodes[i]);
        }
        array_nodes.length = 0;
        for (var i = 0; i < array_line.length; i++)
        {
            map.remove(array_line[i]);
        }
        array_line.length = 0;
        map.setFitView();
        create = false;
    }

    document.querySelector("#add-node").onclick = function() 
    {
        create = true;
    }

    // 查询规划路线
    function queryPlain()
    {
        // 根据起终点经纬度规划驾车导航路线
        var array_way_pos = new Array();
        for (var i = 1; i < array_pos.length - 1; i++)
        {
            array_way_pos.push(new AMap.LngLat(array_pos[i][0], array_pos[i][1]));
        }

       var res = driving.search(new AMap.LngLat(array_pos[0][0], array_pos[0][1]), 
        new AMap.LngLat(array_pos[array_pos.length - 1][0], array_pos[array_pos.length - 1][1]),{
            waypoints: array_way_pos
        }, function(status, result) {
            // result 即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
                //log.success('绘制驾车路线完成')
            } else {
                //log.error('获取驾车数据失败:' + result)
            }
        });
    }

    //创建右键菜单
    var contextMenu = new AMap.ContextMenu();

    //右键放大
    contextMenu.addItem("放大一级", function () {
        map.zoomIn();
    }, 0);

    //右键缩小
    contextMenu.addItem("缩小一级", function () {
        map.zoomOut();
    }, 1);

    //右键显示全国范围
    contextMenu.addItem("缩放至全国范围", function (e) {
        map.setZoomAndCenter(4, [108.946609, 34.262324]);
    }, 2);

    //右键添加Marker标记
    contextMenu.addItem("添加标记", function (e) {
        var marker = new AMap.Marker({
            map: map,
            position: contextMenuPositon //基点位置
        });
    }, 3);

    //地图绑定鼠标右击事件——弹出右键菜单
    map.on('rightclick', function (e) {
        contextMenu.open(map, e.lnglat);
        contextMenuPositon = e.lnglat;
    });

    // 创建纯文本标记
    var text = new AMap.Text({
        text:'文本标记',
        anchor:'center', // 设置文本标记锚点
      //  draggable:true,
        cursor:'pointer',
        angle:0,
        style:{
            'padding': '.75rem 1.25rem',
            'margin-bottom': '1rem',
            'border-radius': '.25rem',
            'background-color': 'white',
            'width': '15rem',
            'border-width': 0,
            'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
            'text-align': 'center',
            'font-size': '20px',
            'color': 'blue'
        },
        position: [112.881898, 28.227956]
    });

    text.setMap(map);
</script>
</body>
</html>

    效果如下: 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!