--- title: GeoTools-快速起步 date: 2023-11-19 author: ac categries: - GIS tags: - GeoTools --- ### GeoTools-快速起步 #### 1.maven构建 ```shell mvn archetype:generate -DgroupId=org.geotools -DartifactId=tutorial -Dversion=1.0-SNAPSHOT -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart ``` > archetype的意思就是模板原型的意思,原型是一个Maven项目模板工具包。 ![image-20231120113304413](./images/image-20231120113304413.png) #### 2. 添加依赖 ```xml UTF-8 1.7 1.7 31-SNAPSHOT true osgeo OSGeo Release Repository https://repo.osgeo.org/repository/release/ false true osgeo-snapshot OSGeo Snapshot Repository https://repo.osgeo.org/repository/snapshot/ true false junit junit 4.13.2 test org.geotools gt-shapefile ${geotools.version} org.geotools gt-swing ${geotools.version} ``` #### 3. 主程序 ```java import java.io.File; import java.util.logging.Logger; import org.geotools.api.data.FileDataStore; import org.geotools.api.data.FileDataStoreFinder; import org.geotools.api.data.SimpleFeatureSource; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.map.MapContent; import org.geotools.styling.SLD; import org.geotools.api.style.Style; import org.geotools.swing.JMapFrame; import org.geotools.swing.data.JFileDataStoreChooser; /** * Prompts the user for a shapefile and displays the contents on the screen in a map frame. * *

This is the GeoTools Quickstart application used in documentationa and tutorials. * */ public class Quickstart { /** * GeoTools Quickstart demo application. * Prompts the user for a shapefile and displays its * contents on the screen in a map frame */ public static void main(String[] args) throws Exception { 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); } } ``` 选择一份`shp`文件,程序会读取该文件添加到mapContent面板中。 image-20231120142008338 注意:shp文件没有被加载到内存中,而是每次需要时都从磁盘读取它。这种方式允许您处理大于内存的数据集。 #### 4. advance 为了更好的交互体验,我们可以通过`DataStoreFinder`获取数据源时添加额外的参数,如设置缓存、创建空间索引等方法来优化。 ```java File file = JFileDataStoreChooser.showOpenFile("shp", null); Map params = new HashMap<>(); params.put("url", file.toURI().toURL()); params.put("create spatial index", true); params.put("memory mapped buffer", true); params.put("charset", "UTF-8"); DataStore store = DataStoreFinder.getDataStore(params); SimpleFeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]); ```