在平时工作中会涉及一些空间范围的操作,比如两个面求交集,求一个多边形的面积等等,一般都会用到JTS。JTS支持点线面的很多操作,关键字为point、linestring、polygon。
JTS没有直接表示圆的关键字,一般用一个多边形表示圆:
1,确定边数
2,画一个环线
3,根据环线生成面
public class JtsTest {
private static GeometryFactory geometryFactory = new GeometryFactory();
public static Polygon createCircle(double x, double y, final double RADIUS) {
final int SIDES = 32; // 确定边数
Coordinate coords[] = new Coordinate[SIDES + 1];
for (int i = 0; i < SIDES; i++) {
double angle = ((double) i / (double) SIDES) * Math.PI * 2.0;
double dx = Math.cos(angle) * RADIUS;
double dy = Math.sin(angle) * RADIUS;
coords[i] = new Coordinate((double) x + dx, (double) y + dy);
}
coords[SIDES] = coords[0];
LinearRing ring = geometryFactory.createLinearRing(coords); // 画一个环线
Polygon polygon = geometryFactory.createPolygon(ring, null); // 生成一个面
return polygon;
}
public static void main(String[] args) throws ParseException {
Polygon p = createCircle(116.45224995263672, 39.988073630126955, 1);
System.out.println(p);
}
}
接下来用openlayers看一下生成的polygon长什么样子。
<!DOCTYPE html>
<html>
<head>
<title>WKT</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var wkt = '';// 把上面生成的polygon复制到这里
var format = new ol.format.WKT();
var feature = format.readFeature(wkt, {
dataProjection: 'EPSG:4326'
});
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
features: [feature]
})
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [108.560121,36.364153],
projection: 'EPSG:4326',
zoom: 4
})
});
</script>
</body>
</html>
结果如下图:
说明:
1,第一段代码来自网络其他博客,出处忘记记录,抱歉。
2,第二段代码来自openlayers官网示例,出处:http://openlayers.org/en/latest/examples/wkt.html?q=wkt