jsp中调用高德地图并截屏上传示例

场景:微信环境中用户授权定位,截取用户位置信息做上传

一、可能存在出现的问题(本人遇到的)

1.html2canvas无法截取高德地图

解决方式:修改html2canvas.js中的源码

 function ImageContainer(src, cors) {
        this.src = src;
        this.image = new Image();
        var self = this;
        this.tainted = null;
        this.promise = new Promise(function(resolve, reject) {
            self.image.onload = resolve;
            self.image.onerror = reject;
            if (cors) {
                //self.image.crossOrigin = "anonymous";
               self.image.crossOrigin = "";//修改为

            }
           // self.image.src = src;
            self.image.src = src+"?"+new Date().getTime();//修改为
            if (self.image.complete === true) {
                resolve(self.image);
            }
        });
    }

2.刷新页面后,高德地图出现空白,无法显示

检测用户的刷新行为,存在将存在的地图移除清空
解决方式:

 // 第一步是检查sessionStorage的一些预定义的值,如果它存在,就提醒用户。
    // 第二步是将sessionStorage设置为某个值(比如说true)
    if (sessionStorage.getItem('reloaded') != null) {
        sessionStorage.removeItem("location")
        // 存在session 说明已经访问过
        console.log('page was reloaded');
    } else {
        //获取当前位置(方法名)
        console.log('page was not reloaded');
    }
    // 同时,创建一个session
    sessionStorage.setItem('reloaded', 'yes'); 

3.截取的地图显示不全或者显示一半

解决方式:
jsp中调用高德地图并截屏上传示例_第1张图片

 var opts = {
                scale: scale, // 添加的scale 参数
                canvas, //自定义 canvas
                logging: true, //日志开关,便于查看html2canvas的内部执行流程
                width: width, //dom 原始宽度
                height: height,
                scrollY: 0,
                scrollX: 0,
                useCORS: true, // 【重要】开启跨域配置
                allowTaint: false
            };

二、核心的示例代码

1.html2canvas.js文件修改的

 function ImageContainer(src, cors) {
        this.src = src;
        this.image = new Image();
        var self = this;
        this.tainted = null;
        this.promise = new Promise(function(resolve, reject) {
            self.image.onload = resolve;
            self.image.onerror = reject;
            if (cors) {
                //self.image.crossOrigin = "anonymous";
               self.image.crossOrigin = "";

            }
           // self.image.src = src;
            self.image.src = src+"?"+new Date().getTime();
            if (self.image.complete === true) {
                resolve(self.image);
            }
        });
    }

2.高德地图引用的文件mAmplbs.js

//用户位置定位   使用geolocation定位
var mMap = function () {
    function rad(d) {
        return d * Math.PI / 180.0;
    }

    this.map = {},
        this.geolocation = {},
        this.k = 0,
        //加载地图,调用浏览器定位服务
        this.initMap = function (num, mapContainer, completFunc, ranking, img) {
                    if (typeof (AMap) == "object") {
                this.map = new AMap.Map(mapContainer, {
                        resizeEnable: true,
                        center: [116.3975, 39.909],
                        WebGLParams: {
                            preserveDrawingBuffer: true
                        }
                    }
                );
                this.map.plugin('AMap.Geolocation', function () {
                    this.geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,//是否使用高精度定位,默认:true
                        timeout: 10000,          //超过10秒后停止定位,默认:无穷大
                        maximumAge: 0,           //定位结果缓存0毫秒,默认:0
                        convert: true,           //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
                        showButton: true,        //显示定位按钮,默认:true
                        buttonPosition: 'RT',    //定位按钮停靠位置,默认:'LB',左下角 /* LT LB RT RB */
                        buttonOffset: new AMap.Pixel(10, 10),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
                        showMarker: true,        //定位成功后在定位到的位置显示点标记,默认:true
                        showCircle: true,        //定位成功后用圆圈表示定位精度范围,默认:true
                        panToLocation: false,     //定位成功后将定位到的位置作为地图中心点,默认:true
                        zoomToAccuracy: false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
                    });
                    this.map.addControl(this.geolocation);
                    AMap.event.addListener(this.geolocation, 'complete', onComplete);//返回定位信息
                    AMap.event.addListener(this.geolocation, 'error', onError);      //返回定位出错信息
                });

                function onComplete(data) {
                    if (completFunc) {
                        completFunc(data);
                    }
                }

                function onError(data) {
                    var str = '定位失败,';
                    str += '错误信息:'
                    switch (data.info) {
                        case 'PERMISSION_DENIED':
                            str += '浏览器阻止了定位操作';
                            break;
                        case 'POSITION_UNAVAILBLE':
                            str += '无法获得当前位置';
                            break;
                        case 'TIMEOUT':
                            str += '定位超时';
                            break;
                        default:
                            str += '未知错误';
                            break;
                    }
                    console.log(str)
                   // alert(str)
                }

                //实例化信息窗体
                var content = [];
                content.push(`<img src=${img}>`);
                if (ranking == -1) {
                    //alert(ranking)
                    content.push(`<p>您所在的城市已有${num}位校友点亮成功</p>`);
                }
                // if (ranking!=-1){
                //     content.push(`<div>
                //         <p>您是第${ranking}位点亮地图者</p>
                //         <p>您所在的城市已有${num}位校友点亮成功</p>
                //     </div>`);
                // }


                var infoWindow = new AMap.InfoWindow({
                    isCustom: true,  //使用自定义窗体
                    content: createInfoWindow(content.join('')),
                    offset: new AMap.Pixel(30, -40)//-110
                });
                //添加marker标记
                // function addMarker() {
                this.map.clearMap();
                var marker = new AMap.Marker({
                    map: this.map,
                    position: [116.3975, 39.909]
                });
                infoWindow.open(this.map, marker.getPosition());
            }
        },
        //构建自定义信息窗体
        this.createInfoWindow = function (content) {
            var info = document.createElement("div");
            info.className = "content-window-card";
            // 定义中部内容
            var middle = document.createElement("div");
            middle.className = "info-middle";
            middle.innerHTML = content;
            info.appendChild(middle);
            return info;
        }
    //关闭信息窗体
    this.closeInfoWindow = function () {
        map.clearInfoWindow();
    }
    this.getCurrentPosition = function (callback) {
        if (typeof (this.geolocation.getCurrentPosition) != 'undefined') {
            this.geolocation.getCurrentPosition();
        } else {
            setTimeout(function () {
                //将获得的经纬度信息,放入sessionStorge
                this.getSessionLocation(callback)
            }, 200)
        }

    },
        this.distance = function (obj1, obj2) {//return:m
            var lng = new AMap.LngLat(obj1.lng, obj1.lat);
            var lag = new AMap.LngLat(obj2.lng, obj2.lat);
            var ss = lng.distance(lag);
            return ss;
        },
        this.getSessionLocation = function (callback, num, ranking, img) {
            if (sessionStorage.getItem('location')) {
                callback();
            } else {
                this.initMap(num, 'container', function (data) {
                    sessionStorage.setItem("location", JSON.stringify(data))
                    callback();
                }, ranking, img);
                this.getCurrentPosition(callback);
            }
        },

        /*
            *两点之间的距离
        *(lng1.lat1)地址一的经纬度
        *(lng2.lat2)地址一的经纬度
        *单位米
        */
        this.serverDistance = function (obj1, obj2) {//return:m
            var radLat1 = rad(obj1.lat);
            var radLat2 = rad(obj2.lat);
            var a = radLat1 - radLat2;
            var b = rad(obj1.lng) - rad(obj2.lng);
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378137;
            s = Math.round(s * 10000) / 10000;
            return s;
        }
    return this;
}();

3.H5页面的代码

   <script type="text/javascript"
            src="https://webapi.amap.com/maps?v=1.4.9&key=${lightPlat.key}">
    </script>
<script src="resources/lightPlat/js/mAmaplbs.js"></script>
<script src="resources/lightPlat/js/html2canvas.js"></script>
<script>

    // 第一步是检查sessionStorage的一些预定义的值,如果它存在,就提醒用户。
    // 第二步是将sessionStorage设置为某个值(比如说true)
    if (sessionStorage.getItem('reloaded') != null) {
        sessionStorage.removeItem("location")
        // 存在session 说明已经访问过
        console.log('page was reloaded');
    } else {
        //获取当前位置(方法名)
        console.log('page was not reloaded');
    }
    // 同时,创建一个session
    sessionStorage.setItem('reloaded', 'yes'); // could be anything

    function timer(obj) {
        $(obj).find('.record_ul').animate({
            marginTop: "-39px"
        }, 500, function () {
            $(this).css({marginTop: "0px"}).find("p:first").appendTo(this);
        })
    }

    mMap.getSessionLocation(locationFunc, ${citySum}, -1, '${headImg}')
    function locationFunc() {
        var data = JSON.parse(sessionStorage.getItem("location"));
        $("#latitude").val(data.position.lat);//纬度
        $("#longitude").val(data.position.lng);//经度

    }

        setTimeout(function () {
            drawImage('container')
        }, 2000)
        //截屏操作
        function drawImage(Boxid) {
            const cntElem = document.getElementById(Boxid);
            // var shareContent = cntElem; //需要截图的包裹的(原生的)DOM 对象
            var width = cntElem.offsetWidth; //获取dom 宽度
            var height = cntElem.offsetHeight; //获取dom 高度
            var canvas = document.createElement("canvas"); //创建一个canvas节点
            var scale = 2; //定义任意放大倍数 支持小数
            canvas.width = width * scale
            canvas.height = height * scale
            canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
            var opts = {
                scale: scale, // 添加的scale 参数
                canvas, //自定义 canvas
                logging: true, //日志开关,便于查看html2canvas的内部执行流程
                width: width, //dom 原始宽度
                height: height,
                scrollY: 0,
                scrollX: 0,
                useCORS: true, // 【重要】开启跨域配置
                allowTaint: false
            };
            html2canvas(cntElem, opts).then(canvas => {
                var context = canvas.getContext('2d');
                context.mozImageSmoothingEnabled = false;
                context.webkitImageSmoothingEnabled = false;
                context.msImageSmoothingEnabled = false;
                context.imageSmoothingEnabled = false;
                var url34 = canvas.toDataURL("image/png");
                var formData = new FormData();
                formData.append('file', dataUrlToBlob(url34));
                $.ajax({
                    type: "POST",
                    url: "up/identity_imgs",//上传图片
                    // data: JSON.stringify(formData),
                    data: formData,
                    dataType: "JSON",
                    processData: false, // jQuery不要去处理发送的数据
                    contentType: false, // jQuery不要去设置Content-Type请求头
                    success: function (data) {
                        if (data.flag == "success") {
                            console.log(data)
                            $("#userPic").val(data.comUrl);
        

                        } else {
                            alert("网络异常,请重新尝试");
                        }
                    }

                })


            });
        }

     // 将base64转成图片文件流
        function dataUrlToBlob(dataUrl) {
            let arr = dataUrl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                // arr[0]是data:image/png;base64
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);

            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }

            let imgFile = new Blob([u8arr], {
                type: mime
            });
            return imgFile;
        }
</script>

4.将将base64转成图片文件流

 // 将base64转成图片文件流
        function dataUrlToBlob(dataUrl) {
            let arr = dataUrl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                // arr[0]是data:image/png;base64
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);

            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }

            let imgFile = new Blob([u8arr], {
                type: mime
            });
            return imgFile;
        }

你可能感兴趣的:(jsp,开发总结异常,java,javascript,前端)