地图打印(Print)
输出地图为图片格式,只能输出可视区域地图以及所有的图层。
- 需要设置preserveDrawingBuffer为true
- 可以通过全局设置devicePixelRatio值打印高清图片
ts
const dpi = 300
Object.defineProperty(window, 'devicePixelRatio', {
get() { return dpi / 96 },
})
示例
示例源码
tsx
import React, { useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom'
import { MbMap, MbPolygonLayer, MbTiandituLayer } from '@mapbox-react/core'
const App = () => {
const [mapCenter] = useState([116.38745, 39.91266])
const [zoom, setZoom] = useState(1)
const colors = ['rgba(255,125,0,0.5)', '#ec71a9', 'red']
const [colorIndex, setColorIndex] = useState(0)
const polygonCoordinates = [
{
coordinates: [
[110.56640625, 39.639537564366684],
[107.22656249999999, 36.527294814546245],
[107.57812499999999, 32.39851580247402],
[112.5, 30.600093873550072],
[117.42187500000001, 32.02670629333614],
[117.24609374999999, 36.94989178681327],
[114.697265625, 39.70718665682654],
[110.56640625, 39.639537564366684],
],
},
{
coordinates: [
[82.08984375, 32.47269502206151],
[90.966796875, 32.47269502206151],
[90.966796875, 38.685509760012],
[82.08984375, 38.685509760012],
[82.08984375, 32.47269502206151],
],
},
]
let $map: any
const mapCreatedHandler = (map: any) => {
$map = map
}
const print = () => {
const img = $map?.getCanvas().toDataURL('image/png')
const link = document.createElement('a')
link.setAttribute('href', img)
link.setAttribute('download', 'test.png')
document.body.appendChild(link)
link.click()
}
return (
<div className="map-wrapper">
<MbMap
center={mapCenter}
zoom={zoom}
extendProps={{ preserveDrawingBuffer: true }}
onCreated={mapCreatedHandler}
>
<div style={{ position: 'absolute', top: '5px', left: '5px' }}>
<button className="primary" onClick={print}>
Print
</button>
</div>
<MbTiandituLayer types={['vec']} />
<MbPolygonLayer
data={polygonCoordinates}
color={colors[colorIndex % colors.length]}
outlineColor="yellow"
/>
</MbMap>
</div>
)
}
ReactDOM.render(<App />, document.querySelector('#root'))