高德地图 JS API示例->几何计算->距离/面积计算-> 点到线的距离

高德地图 JS API示例->几何计算->距离/面积计算-> 点到线的距离

使用AMap.GeometryUtil的对应方法,获取折线上距离某点最近的位置、点到线的距离。

<!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" type="text/css">
    <style>
      html,body,#container{
        height: 100%
      }
    </style>
</head>
<body>
<div id="container"></div>
<div class='info'>拖动蓝色Marker可调整位置</div>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
<script type="text/javascript">
    //初始化地图对象,加载地图
    var map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 13
    });
    var pos = [116.377904, 39.915423]
    var marker = new AMap.Marker({
        map: map,
        draggable:true,
        position: pos
    });
    
    
    var path = [
        [116.368904, 39.913423],
        [116.382122, 39.901176],
        [116.387271, 39.912501],
        [116.398258, 39.904600]
    ]
    var polyline = new AMap.Polyline({
        map: map,
        path: path,
        strokeColor:'#80d8ff',
    });
    var polyline2 = new AMap.Polyline({
        strokeStyle:'dashed',
        strokeColor:'blue',
        strokeWeight:2
    });
    polyline2.setMap(map);
    var text = new AMap.Text({
        text:'',
        style:{'background-color':'#ccccff',
                'border-color':'green',
                'font-size':'12px'}
    });
    text.setMap(map);
    marker2 = new AMap.Marker({
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
        offset:new AMap.Pixel(-9,-31)
    });
    marker2.setMap(map);
    
    function compute(){
        var pos = marker.getPosition();
        // 计算path上距离pos最近的点
        var closestPositionOnLine  = AMap.GeometryUtil.closestOnLine(pos,path);
        marker2.setPosition(closestPositionOnLine)
        // 设置label标签
        marker2.setLabel({
            offset: new AMap.Pixel(20, 20),
            content: '折线上离蓝色点最近的点'
        });
        polyline2.setPath([pos,closestPositionOnLine])
        
        var distance = Math.round(AMap.GeometryUtil.distanceToLine(pos,path));
        var textPos = [(pos.lng+closestPositionOnLine[0])/2,(pos.lat+closestPositionOnLine[1])/2]

        text.setPosition(textPos)
        text.setText('点线距离'+distance+'米')
    }
    map.setFitView();
        
    compute();
    marker.on('dragging',compute)

</script>
</body>
</html>
0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x