本文基于mapboxGL
实现地图的分享功能,并通过qrcode.js
生成二维码。
function randomString(len = 32){
//默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
const chars = 'abcdefhijkmnprstwxyz2345678';
let tempLen = chars.length, tempStr='';
for(let i = 0; i < len; ++i){
tempStr += chars.charAt(Math.floor(Math.random() * tempLen ));
}
return tempStr;
}
function generateQrcode(text) {
const size = 200
new QRCode('qrcode', {
text: text,
width: size,
height: size,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
});
}
function shareMap () {
let style = map.getStyle()
style.center = map.getCenter().toArray()
style.zoom = map.getZoom()
const mapId = randomString()
const url = `https://www.lzugis.cn/preview.html?mapId=${mapId}`
document.getElementById('mapUrl').innerText = url
console.log(style)
generateQrcode(url)
}
https://www.lzugis.cn/preview.html?mapId=htfbk4wihpczjkktsxwjbsf254pdtp47
function getQueryString(name) {
const url_string = window.location.href;
const url = new URL(url_string);
return url.searchParams.get(name);
}
const mapId = getQueryString('mapId ')
fetch(`https://www.lzugis.cn/getStyle?mapId=${mapId }`).then(res => res.json()).then(res => {
const map = new mapboxgl.Map({
container: 'map',
style: res,
attributionControl: false
});
})