基于mapbox和truf.js实现地图上测距

/**
 * mapbox实现在地图上测距
 * 先初始化地图得到map对象
 */
function Ceju(map){
    this.map = map;//初始化map
    this.markers = [];//存放markers图标
    this.points = [];//存放点信息
    this.inintClick = true;//判断是否是双击还是单击
    this.tmp = 0;//记录点图层的长度
    this.only = 0;//标识markers
    this.tooltip = "";//初始化创建markers图标
    this.startMarkers = [];//第二次点击测量存放markers图标
    this.jsonPoint = { //点
        "type":"FeatureCollection",
        "features":[]
    }
    this.jsonLine = { //线
        "type":"FeatureCollection",
        "features":[]
    }

}

/**
 * initMap 方法名
 */
Ceju.prototype.initMap = function initMap(){
    this.map.doubleClickZoom.disable();
    this.map.getCanvas().style.cursor = "default";
    const ele = document.createElement("div");
    ele.className = "measure-result";
    let options = {
        element:ele,
        anchor:"left",
        offset:[8,0]
    }
    this.tooltip = new mapboxgl.Marker(options)
    .setLngLat([0,0])
    .addTo(this.map)
    if(this.inintClick){
        this.renderLayer();//渲染图层
        this.map.on("click",function(e){
            let coords = [e.lngLat.lng,e.lngLat.lat];
            this.addMeasureRes();
            this.addPoints();
            this.points.push(coords);
        })
        this.map.on("mousemove",function(e){
            if(this.inintClick){
                let coords = [e.lngLat,e.lngLat];
                if(jsonPoint.features.length-this.tmp>0){
                    let prev = this.jsonPoint.features[this.jsonPoint.features.length-1];
                    this.jsonLine.features.push({
                        "type":"Feature",
                        "properties":{
                            "id":this.only
                        },
                        "geometry":{
                            "type":"LineString",
                            "coordinates":[prev.geometry.coordinates,coords]
                        }
                    })
                    if(this.map.getSource("line-remove")){
                        this.map.getSource("line-remove").setData(this.jsonLine);//添加鼠标移动线数据源
                    }
                    let htmlStr = "<p style= 'color:white;background-color:#434343;padding:2px 5px;'>"+this.getLength(coords)+"</p>"
                    ele.innerHTML = htmlStr;
                    ele.setAttribute("idm",this.only);//添加markers唯一标识
                    this.markers.push(ele);//存储到markers
                }else{
                    ele.innerHTML ="<p style= 'color:white;background-color:#434343;padding:2px 5px;'>点击地图开始测量</p>"
                }
                if(ele.innerText == "点击地图开始测量"){
                    this.startMarkers.push(ele);
                }else{
                    this.markers.push(ele);
                }
                this.tooltip.setLngLat(coords);
            }
        })

        this.map.on("dblclick",function(e){
            if(this.inintClick){
                let coords = [e.lngLat.lng,e.lngLat.lat];
                //处理最后一个markers显示问题
                if(this.jsonPoint.features[this.jsonPoint.features.length-1].geometry.coordinates[0] == e.lngLat.lng &&ethis.jsonPoint.features[this.jsonPoint.features.length-1].coordinates.geometry[1]== e.lngLat.lat){
                    this.markers[this.markers.length-1].children[0].innerText = "总长:"+this.markers[this.markers.length-1].children[0].innerText;
                }
                for(let f = 0; f<this.startMarkers.length;f++){
                    if(this.startMarkers[f].childrenNodes[0].innerHTML =="点击地图开始测量"){
                        this.startMarkers[f].remove();
                    }
                }
                this.map.getCanvas().style.cursor ="";
                this.points = [];//存放点的
                let ele = document.createElement("div");
                ele.className ="close-measure-result";
                ele.setAttribute("id","measure-result_"+this.only);//添加唯一标识div
                ele.setAttribute("idm",this.only);//添加唯一标识markers
                let options = {
                    element:ele,
                    anchor:"bottom-left",
                    offset:[-5,-10]
                }
                new mapboxgl.Marker(options)
                .setLngLat(coords)
                .addTo(this.map)

                this.markers.push(ele);//存储到markers
                //解决两个点在一起问题
                if(document.getElementById("measure-result_"+this.only).previousElementSibling.children[0].innerHTML.split(":")[1]=="起点"){
                    if(document.getElementById("measure-result_"+this.only).previousElementSibling.childNodes[0].innerHTML.indexOf("总长")>-1){
                        document.getElementById("measure-result_"+this.only).previousElementSibling.childNodes[0].innerHTML = "总长:0米";
                    }
                }

                this.only++;//防止第次在地图画测距的时候id重复问题
                let measuers = document.getElementsByClassName("close-measure-result");
                let idMarr = [];//存放markers标识idm
                for(let w= 0;w<measuers.length;w++){
                    idMarr.push(measuers[w].getAttribute("idm"))
                }
                for(let g= 0;g<idMarr.length;g++){
                    let idBox = document.getElementById("measure-result_"+idMarr[g]);
                    idBox.onclick = function(e){
                        this.jsonPoint = this.jsonPoint.filter(item=>item.properties.id!=idMarr[g]);
                        this.jsonLine = this.jsonLine.filter(item=>item.properties.id!=idMarr[g]);
                        this.map.getSource("points").setData(this.jsonPoint);//更新点数据源
                        this.map.getSOurce("line").setData(this.jsonLine);//更新线数据源
                        this.map.getSource("line-remove").setData(this.jsonLine);//更新移动线数据源
                        this.tmp = this.jsonPoint.features.length;//记录还有多少点图层
                        for(let t = 0 ;t<this.markers.length;t++){
                            if(this.markers[t].getAttribute("idm") == idMarr[g]){
                                this.markers[t].remove();
                            }
                        }
                    }
                }
                

            }
        })
    }
    
}


/**
 * renderLayer 方法名
 * 
 */
Ceju.prototype.renderLayer = function renderLayer(){
    let source = this.map.getSource("points");
    if(source){
        this.map.getSource("points").setData(this.jsonPoint);//点
        this.map.getSource("line-remove").setData(this.jsonLine);//线
        this.map.getSource("line").setData(this.jsonLine);//线
    }else{
        this.map.addSource("points",{
            "type":"geojson",
            "data":this.jsonPoint
        })
        this.map.addSource("line",{
            "type":"geojson",
            "data":this.jsonLine
        })
        this.map.addSource("line-remove",{
            "type":"geojson",
            "data":this.jsonLine
        })
        this.map.addLayer({
            "id":"line-remove",
            "type":"line",
            "source":"line-remove",
            "paint":{
                "line-color":"#ff0000",
                "line-width":2,
                "line-opacity":0.65
            }
        })
        this.map.addLayer({
            "id":"line",
            "type":"line",
            "source":"line",
            "paint":{
                "line-color":"#ff0000",
                "line-width":2,
                "line-opacity":0.65
            }
        })
        this.map.addLayer({
            "id":"points",
            "type":"circle",
            "source":"points",
            "paint":{
                "circle-color":"#ff4895",
                "circle-radius":5,
                "circle-stroke-width":2,
                "circle-stroke-color":"#ff4895"
            }
        })
    }
}


/**
 * 点、线图层
 * addPoints 方法名
 * coords 经纬度数组
 */
Ceju.prototype.addPoints = function addPoints(coords){
    if(this.jsonPoint.features.length-this.tmp>0){
        let prev = this.jsonPoint.features[this.jsonPoint.features.length-1];
        this.jsonLine.features.push({
            "type":"Feature",
            "properties":{
                "id":this.only
            },
            "geometry":{
                "type":"LineString",
                "coordinates":[prev.geometry.coordinates,coords]
            }
        })
        if(map.getSource("line")){
            map.getSource("line").setData(this.jsonLine);//添加线数据源
        }
    }
    this.jsonPoint.features.push({
        "type":"Feature",
        "properties":{
            "id":this.only
        },
        "geometry":{
            "type":"Point",
            "coordinates":coords
        }
    })
    this.map.getSource("points").setData(this.addPoints);//添加点数据源
}


/** 添加的点个数和显示距离
 * addMeasureRes 方法名
 * coords 经纬度数组
 */
Ceju.prototype.addMeasureRes = function addMeasureRes (coords){
    const ele = document.createElement("div");
    ele.className = "measuer-result";
    let options = {
        element:ele,
        anchor:"left",
        offset:[8,0]
    }
    let measureLen = this.points.length === 0?"起点": this.getLength(coords);
    if(measureLen == "0米"){
        measureLen ="起点";
    }
    let htmlStr = "<p style='color:white;background-color:#434343;padding:2px 5px;'>"+measureLen+"</p>";
    ele.innerHTML = htmlStr;
    ele.setAttribute("idm",this.only);//添加唯一markers标识
    new mapboxgl.Marker(options)//创建markers图标
    .setLngLat(coords)
    .addTo(this.map)
    this.markers.push(ele);// 存放markers图标
}


/**
 * getLength 方法名
 * coords 经纬度数组
 * truf truf.js插件
 */
Ceju.prototype.getLength = function getLength(){
    let options = this.points.concat([coords]);
    let line  = truf.lineString(options);
    let len = truf.length(line);
    if(len<1){
        len = Math.round(len*100)+"米";
    }else{
        len = len.toFixed(2)+"公里";
    }
    return len;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Mapbox GL JS实现定位打点功能,你需要遵循以下步骤: 1. 创建一个具有定位权限的地图: ```javascript mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [lng, lat], // 设置地图中心点经纬度 zoom: 12 // 设置地图缩放级别 }); // 获取地理位置信息并更新地图中心点 navigator.geolocation.getCurrentPosition(function(position) { var lng = position.coords.longitude; var lat = position.coords.latitude; map.setCenter([lng, lat]); }); ``` 2. 添加定位点: ```javascript var el = document.createElement('div'); el.className = 'marker'; // 创建一个Marker对象并添加到地图中 new mapboxgl.Marker(el) .setLngLat([lng, lat]) .addTo(map); ``` 3. 样式化定位点: ```css .marker { background-image: url('https://docs.mapbox.com/help/demos/custom-markers-gl-js/mapbox-icon.png'); background-size: cover; width: 50px; height: 50px; border-radius: 50%; cursor: pointer; } ``` 4. 完整代码示例: ```html <!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <title>Mapbox GL JS - Add geolocate control</title> <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> <script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js'></script> <link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet' /> <style> body { margin: 0; padding: 0; } #map { position: absolute; top: 0; bottom: 0; width: 100%; } .marker { background-image: url('https://docs.mapbox.com/help/demos/custom-markers-gl-js/mapbox-icon.png'); background-size: cover; width: 50px; height: 50px; border-radius: 50%; cursor: pointer; } </style> </head> <body> <div id='map'></div> <script> mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [0, 0], // 设置地图中心点经纬度 zoom: 12 // 设置地图缩放级别 }); // 获取地理位置信息并更新地图中心点 navigator.geolocation.getCurrentPosition(function(position) { var lng = position.coords.longitude; var lat = position.coords.latitude; map.setCenter([lng, lat]); // 创建定位点 var el = document.createElement('div'); el.className = 'marker'; new mapboxgl.Marker(el) .setLngLat([lng, lat]) .addTo(map); }); </script> </body> </html> ``` 这个示例代码会在地图上显示一个定位点,该点的位置是根据用户的当前位置动态确定的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值