node-mapnik安装过程略,我们使用geojson为数据源,也可以使用其他的数据源,这里为了简单 直接上代码point.json
{
"type": "FeatureCollection",
"features": [{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 113.44397, 23.094416 ] } },...] }
编写mapnik.map 需要用到的tile.xml
<Map srs="+init=epsg:4326">
<Style name="light">
<Rule>
<!-- 点样式,默认黑色-->
<PointSymbolizer file="../img/mass1.png" transform="scale(0.1)" allow-overlap="yes" ignore-
placement="yes" />
</Rule>
</Style>
<Layer name="lightlayer" srs="+init=epsg:4326" >
<StyleName>light</StyleName>
</Layer>
</Map>
瓦片需要用到x,y,z三个参数,使用mapnik自带类转换,也可以用自定义类转换来实现特殊瓦片 例如百度(百度的瓦片规则从中心开始0,0 默认的规则是左上角0,0) 使用express做网络服务,直接上代码app.js
const express = require('express')
const app = express()
const port = 3000
var mapnik = require('mapnik')
var fs = require('fs')
const fileh = './data/point.json'
mapnik.register_default_fonts()
mapnik.register_default_input_plugins()
var geojson = fs.readFileSync(fileh, 'utf-8');
app.get('/map/title/:x-:y-:z.png', (req, res) => {
var vt = new mapnik.VectorTile(+req.params.z, +req.params.x, +req.params.y);
vt.addGeoJSON(geojson, 'lightlayer', {});
var tileSize = vt.tileSize;
var map = new mapnik.Map(tileSize, tileSize);
map.load('./test/tile.xml', function (err, map) {
vt.render(map, new mapnik.Image(256, 256), function (err, image) {
if (err) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err.message);
} else {
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(image.encodeSync('png'));
}
});
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
启动node app.js, 访问 localhost:3000/map/title/0-0-0.png, x,y,z自由替换,再加个定时更新geojson任务,监听json文件修改 替换geojson变量,简单瓦片服务就完成了
来源:oschina
链接:https://my.oschina.net/u/210357/blog/4269055