GeoTools判斷一個點是否在多邊形上

https://repo.osgeo.org/service/rest/repository/browse/release/org/geotools
http://docs.geotools.org/latest/userguide/library/jts/index.html
https://sourceforge.net/projects/geotools/files/GeoTools%2023%20Releases/23.0/
https://github.com/geotools/geotools

        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts</artifactId>
            <version>1.13</version>
        </dependency>
import com.vividsolutions.jts.algorithm.PointLocator;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.operation.buffer.BufferOp;

	/**
	 * 判斷以x,y爲座標的點point(x,y)是否在geometry表示的Polygon中
	 * @param x
	 * @param y
	 * @param geometry wkt格式 POLYGON((0 0, 10 0, 10 10, 0 10,0 0))
	 * @return
	 */
	public boolean withinGeo(double x,double y,String geometry) throws ParseException {
		GeometryFactory geometryFactory = new GeometryFactory();
		Coordinate coord = new Coordinate(x,y);
		Point point = geometryFactory.createPoint( coord );
		WKTReader reader = new WKTReader( geometryFactory );
		Polygon polygon = (Polygon) reader.read(geometry);
		return point.within(polygon);
	}
	
		public static void main(String[] args) throws IOException, ParseException {
		String wktPoly = "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))"; //請自行搜素瞭解wkt格式
		String wktPoint = "POINT (30 30)";
		GeometryFactory geometryFactory = new GeometryFactory();
		WKTReader reader = new WKTReader(geometryFactory);
		Geometry point = reader.read(wktPoint);
		Geometry poly = reader.read(wktPoly);
		boolean ex = poly.contains(point);
		System.out.println("ex = " + ex);
		LineString geometry = (LineString) reader.read("LINESTRING(0 0, 2 0, 5 0)");
		LineString geometry2 = (LineString) reader.read("LINESTRING(5 0, 0 0)");
		boolean b = geometry.equals(geometry2);
		System.out.println("b = " + b);
		System.out.println(withinGeo(5,5,"POLYGON((0 0, 10 0, 10 10, 0 10,0 0))"));
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章