使用mapbox-sdk-js使用以下代码创建的png文件不可读,但响应 header 显示内容“image/png”,状态代码为200。这不是我的 token 的问题,否则,如果我使用带有相同参数的curl,我得到了一个正确的PNG文件(和一个漂亮的 map )。
你能帮我将回复保存到文件中吗?谢谢!
const mbxStatic = require('@mapbox/mapbox-sdk/services/static')
const fs = require('fs')
// Get config
const MAPBOX_TOKEN = process.env.MAPBOX_TOKEN
const staticClient = mbxStatic({ accessToken: MAPBOX_TOKEN })
staticClient
.getStaticImage({
ownerId: 'mapbox',
styleId: 'streets-v10',
width: 200,
height: 300,
position: {
coordinates: [-77, 38],
zoom: 5
}
})
.send()
.then(response => {
const image = response.body
console.log(response.headers)
fs.writeFileSync("./map.png", image, 'binary')
}).catch(error => console.log(error));
最佳答案
所以我和你有同样的问题。 我的解决方案是添加一个泵函数并使用 createWriteStream 函数保存结果。
此外,我没有使用 staticClient,而是使用了来自 mapBox 静态 Playground 的链接。
const { promisify } = require('util');
const request =require('request');
const fs = require('fs');
await pump(request(url), fs.createWriteStream('./map.png', {encoding: 'base64'}));
但我想如果您替换请求调用,您也可以保存 staticClient 的响应。不过没试过。
关于node.js - 使用 Node sdk js 将 Mapbox 静态 api 响应保存到 png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54117885/