天天看點

java畫兩條線_java – 如何使用Geotools在shapefile上繪制一條線

我有一個打開的shapefile,看起來像這樣:

現在我試圖從我點選該地圖的兩個點畫一條線;但是他們為QuickStart.java示例提供的代碼異常模糊.

這是他們的代碼:

package org.geotools.tutorial;

import java.io.File;

import org.geotools.data.FileDataStore;

import org.geotools.data.FileDataStoreFinder;

import org.geotools.data.simple.SimpleFeatureSource;

import org.geotools.map.FeatureLayer;

import org.geotools.map.Layer;

import org.geotools.map.MapContent;

import org.geotools.styling.SLD;

import org.geotools.styling.Style;

import org.geotools.swing.JMapFrame;

import org.geotools.swing.data.JFileDataStoreChooser;

import org.geotools.geometry.jts.JTSFactoryFinder;

import com.vividsolutions.jts.geom.Coordinate;

import com.vividsolutions.jts.geom.LineString;

public class Quickstart {

public static void main(String[] args) throws Exception {

// display a data store file chooser dialog for shapefiles

File file = JFileDataStoreChooser.showOpenFile("shp", null);

if (file == null) {

return;

}

FileDataStore store = FileDataStoreFinder.getDataStore(file);

SimpleFeatureSource featureSource = store.getFeatureSource();

// Create a map content and add our shapefile to it

MapContent map = new MapContent();

map.setTitle("Quickstart");

Style style = SLD.createSimpleStyle(featureSource.getSchema());

Layer layer = new FeatureLayer(featureSource, style);

map.addLayer(layer);

// Now display the map

JMapFrame.showMap(map);

}

}

現在,我感到困惑的是,我應該用什麼方法點選兩個點并在它們之間畫一條線?

有沒有人有這方面的好資源?我已經閱讀了GeoTools文檔并且仍然有點困惑.

我試圖在網站上執行通用代碼,但它沒有出現在地圖上.

GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory( null );

Coordinate[] coords =

new Coordinate[] {new Coordinate(0, 2), new Coordinate(2, 0), new Coordinate(8, 6) };

LineString line = geometryFactory.createLineString(coords);

Style style2 = SLD.createLineStyle(Color.BLUE, 1);

Layer layer2 = new FeatureLayer(featureSource, style2);

最佳答案 将行添加到可以添加到圖層的集合中:

>您應該從LineString建立一個SimpleFeature(這樣幾何線實際上得到GeoReferenced).確定添加逼真的坐标:第二個剪切的坐标将産生一個相對較小的線.

>建立一個新的DefaultFeatureCollection(存儲器存儲的集合),您可以添加SimpleFeature. (現在,在第二次剪切時,該線未添加到任何地方進行繪制.)

DefaultFeatureCollection lineCollection = new DefaultFeatureCollection();

lineCollection.add(simpleFeature);

>将DefaultFeatureCollection而不是FeatureSource添加到新建立的圖層作為構造函數參數.

Layer layer = new FeatureLayer(lineCollection, style);

>将圖層添加到地圖中,就像在第一個剪切中一樣.

map.addLayer(layer);

有關SimpleFeature的建立,另請參見Feature Tutorial