PARSEPATH

作者: 黄鑫鑫鑫鑫 | 来源:发表于2017-06-04 12:57 被阅读30次

    function parsePath(info){

    let { path, zoom, offset } = info;
    
    var steps = path.steps;
    var lineArr = [];
    steps.forEach(function(item, index){
        var tmparr = item.polyline.split(";");
        var tmp = tmparr.map(function(val){
            return val.split(",");
        });
        lineArr = lineArr.concat(tmp);
    });
    
    var pxarr = lineArr.map(function(item){
        return project({
            lng : item[0],
            lat : item[1]
        }, 20);
    });
    
    var pas = [];
    var ratio = Math.pow(2, 20 - zoom);
    pxarr.forEach(function(item, index){
        if(index % 4 === 0) {
            pas.push([((item.x - offset.x) /ratio).toFixed(6),((item.y - offset.y)/ratio).toFixed(6)]);
        }
    });
    
    return pas;
    

    }

    function pathLength(pas) {

    var len = 0;
    var i = 1;
    if(pas && pas.length) {
        for( i; i<pas.length; i++){
            var a = pas[i][0] - 0 - pas[i-1][0];
            var b = pas[i][1] - 0 - pas[i-1][1];
            len += Math.sqrt( a * a + b * b );
        }
    }
    return len;
    

    }

    function fetchPath(opt){

    var from = opt.origin.x + "," + opt.origin.y;
    var to = opt.dest.x + "," + opt.dest.y
    var url = "http://restapi.amap.com/v3/direction/driving?key=ac92f92386cfe54122ae34476aafb03e&extensions=base&strategy=" + parseInt(1 + 20 * Math.random()) + "&origin=" + from + "&destination=" + to;
    fetch(url)
    .then( (res) => {
        return res.json();
    })
    .then( (json) => {
        return {
            path : json.route.paths[0],
            zoom : opt.zoom,
            offset : opt.offset
        };
    })
    .then( parsePath )
    .then( (pas) => {
    
        var len = pathLength(pas);
    
        postMessage({
            path : pas,
            len : len,
            opt : opt
        });
    });
    

    }

    相关文章

      网友评论

          本文标题:PARSEPATH

          本文链接:https://www.haomeiwen.com/subject/hmmvfxtx.html