当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 百度地图/高德地图大批量坐标转换结果返回顺序问题

百度地图/高德地图大批量坐标转换结果返回顺序问题

2018年11月02日  | 移动技术网IT编程  | 我要评论

转载请注明出处:https://www.cnblogs.com/joanna-yan/p/9894712.html 

  项目需求:设备采集到的gps坐标信息,需提供实时、历史轨迹的查看功能。这些点坐标除经纬度信息外还携带了其它的信息,比如:速度、方向、解状态等。原始的gps坐标需要转换成百度地图/高德地图坐标后才能在相应的地图上显示,否则存在较大的位置偏差。

  前端人员在高德地图上显示多个点坐标信息时,发现转换后回来的坐标点没法与该坐标点的其它信息对应。一直得不到解决。

帮忙查看,调试代码。发现高德/百度地图坐标转换方法是异步的,包括js api和http请求的uri方式。

https://lbs.amap.com/api/javascript-api/reference/lnglat-to-address#t2 

http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition

可以看到该方法不支持传参的扩展和属性附带。所以通过将坐标的其它属性附带到坐标的异步转换方法,再通过结果一起带回来的办法是行不通了。

方法是异步的,回调函数回调就会有时间延迟。如果按照for循环顺序去提交转换,其回调函数也不是顺序执行的。

也就是说,你连续提交了1、2、3、4、5,5个gps坐标,其回调函数的回调顺序有可能是43521,或其他,是无需的。

一次性传一组坐标进行转换,回调返回结果的坐标数组里面的顺序也是改变了的。

最后通过递归解决。再次记录下思路。

那么我们如何保证返回结果有序?

  我们可以一次性转换一个gps坐标,等回调函数回调成功后在地图上添加覆盖物,再进行下一个坐标的转换。依次保证数据顺序不会乱。

以高德地图为例,用简单的代码模拟下:

<script type="text/javascript">
    var map = new amap.map('container', {
        zoom: 12,
        center: [121.532327,31.148761]
    });

    var a = [1,2,3,4,5,6,7,8];//模拟坐标解状态
    var onlinelinarr = [
           new amap.lnglat(121.528,31.1509),
           new amap.lnglat(121.428,31.1503),
           new amap.lnglat(121.328,31.1505),
           new amap.lnglat(121.468,31.1508),
           new amap.lnglat(121.478,31.1506),
           new amap.lnglat(121.488,31.1504),
           new amap.lnglat(121.498,31.1502),
           new amap.lnglat(121.418,31.1503),
       ];
     var k = 0;
        
    function convertfrom(lnglat){
        amap.convertfrom(lnglat, 'gps',  (status, result) => {
            console.log(status);
            var onlinelngx,onlinelaty,onlinegdlngx,onlinegdlaty;
            if(result.info === 'ok'){
                var gdlinarr = result.locations;
                for (var i = 0; i < gdlinarr.length; i++) {
                    onlinegdlngx = gdlinarr[i].lng;
                    onlinegdlaty = gdlinarr[i].lat;
                }
                
            }
            
            if(status === 'complete'){
                if(k < onlinelinarr.length-1){
                    var j = ++k;
                    console.log(a[j]);
                    convertfrom(onlinelinarr[j]);

                    if(a[j] == 1){
                        imgfunc('red.png',onlinegdlngx,onlinegdlaty);
                    }else if(a[j] == 2){
                        imgfunc('green.png',onlinegdlngx,onlinegdlaty);
                    }else{
                          imgfunc('startpoint.png',onlinegdlngx,onlinegdlaty);
                    }
                }
            }
        });
    }
    convertfrom(onlinelinarr[k]);
    console.log(a[k]);

   function imgfunc (img,x,y) {
        var marker = new amap.marker({
            map:map,
            position:new amap.lnglat(x, y), 
            icon:img,  
            // autorotation:true,
        });
    }     
</script>

如果此文对您有帮助,微信打赏我一下吧~

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网