Leaflet的强大之处在于轻量,并可以通过许多插件进行扩展。
以下介绍两个JS
Leaflet.PM https://github.com/codeofsumit/leaflet.pm
Leaflet.PM Demo https://geoman.io/studio/
Leaflet.PM,可自由在地图上勾画矢量,并可通过Leaflet 自带的 toGeoJSON() 转成GeoJson对象,持久化到数据库,或转化成json文件用于数据移植等。
GeoJson 介绍 https://www.oschina.net/translate/geojson-spec
Turf.js http://turfjs.org/
Turf.js主要用实现在网页端来空间几何对象关系的计算,点、线、面之间包含、相交等一系统运算
通过Leaflet.PM与Turf.js的结合,我们可以做出一些比较有意思的东西。
1、合并复杂多边形
思路:通过Leaflet.pm 用map.on('pm:create', listenerCreatePm); 监听地图勾画事件,将创建好的layer转化为turf.polygon对象,调用turf.union(poly1, poly2); 即可拿到合并后的多边形,若为复杂多边形,则多个多边形依次合并即可。
var poly1 = turf.polygon([[
[-82.574787, 35.594087],
[-82.574787, 35.615581],
[-82.545261, 35.615581],
[-82.545261, 35.594087],
[-82.574787, 35.594087]
]], {"fill": "#0f0"});
var poly2 = turf.polygon([[
[-82.560024, 35.585153],
[-82.560024, 35.602602],
[-82.52964, 35.602602],
[-82.52964, 35.585153],
[-82.560024, 35.585153]
]], {"fill": "#00f"});
var union = turf.union(poly1, poly2);
效果图
2、获取多边形相交部分
思路: 通过Leaflet.pm 用map.on('pm:create', listenerCreatePm); 监听地图勾画事件,将创建好的layer转化为turf.polygon对象,调用turf.intersect(poly1, poly2); 即可拿到相交部分
var poly1 = turf.polygon([[
[-122.801742, 45.48565],
[-122.801742, 45.60491],
[-122.584762, 45.60491],
[-122.584762, 45.48565],
[-122.801742, 45.48565]
]]);
var poly2 = turf.polygon([[
[-122.520217, 45.535693],
[-122.64038, 45.553967],
[-122.720031, 45.526554],
[-122.669906, 45.507309],
[-122.723464, 45.446643],
[-122.532577, 45.408574],
[-122.487258, 45.477466],
[-122.520217, 45.535693]
]]);
var intersection = turf.intersect(poly1, poly2);
效果图(蓝色部分为相交)