geotools连接PostgreSQL数据库

geotools快速入门

GeoTools是一个开放源代码(LGPL)Java代码库,它提供了符合标准的方法来处理地理空间数据,例如实现地理信息系统(GIS)。

步骤

参照官网:https://geotools.org/
geotools连接PostgreSQL数据库_第1张图片
我使用的是idea
geotools连接PostgreSQL数据库_第2张图片
其实我创建的时候并不是按照官网上的步骤来的,因为我比较习惯从https://start.spring.io/
上面构建一个新的maven项目,填写命名下载压缩包,然后在idea中打开。
pom中增加依赖包:

	
		1.8
		UTF-8
		24-SNAPSHOT
	
    
        
            junit
            junit
            4.11
            test
        
        
            org.geotools
            gt-shapefile
            ${geotools.version}
        
        
            org.geotools
            gt-swing
            ${geotools.version}
        
    
    
      
        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
      
    

测试一下

/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2019, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 */

package org.geotools.tutorial.quickstart;

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;

/**
 * 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 { // 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); } }

运行,打开shp文件
geotools连接PostgreSQL数据库_第3张图片
geotools连接PostgreSQL数据库_第4张图片

连接PostgreSQL数据库

在网上找到geotools连接数据库的资料,
参考:https://www.cnblogs.com/tuboshu/p/10752286.html
但是发现导入依赖失败
geotools连接PostgreSQL数据库_第5张图片
最后看到这个:https://www.jianshu.com/p/e04f486b7954
但是还是失败了,经过多次尝试,终于找到正确的依赖包。

	
		1.8
		UTF-8
		24-SNAPSHOT
	

	
		
			org.springframework.boot
			spring-boot-starter
		

		
			junit
			junit
			4.11
			test
		
		
			org.geotools
			gt-shapefile
			${geotools.version}
		
		
			org.geotools
			gt-swing
			${geotools.version}
		
		
			org.geotools
			gt-geojson
			${geotools.version}
		
		
			org.geotools
			gt-epsg-hsql
			${geotools.version}
		
		
		
			org.geotools.jdbc
			gt-jdbc-postgis
			${geotools.version}
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
			
				
					org.junit.vintage
					junit-vintage-engine
				
			
		
	

		
			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
		
		
			maven2-repository.dev.java.net
			Java.net repository
			http://download.java.net/maven/2
		
	

geotools连接PostgreSQL数据库_第6张图片
接下来就是上代码:

package com.geotools.geotoolsdemo;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.simple.SimpleFeature;

import org.geotools.data.postgis.PostgisNGDataStoreFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: geotoolsdemo
 * @description: 连接数据库
 * @author: zhudan
 * @create: 2020/6/18 18:45
 */
public class PostGis {
    /**
     * @param dbtype:    数据库类型,postgis or mysql
     * @param host:      ip地址
     * @param port:      端口号
     * @param database:  需要连接的数据库
     * @param userName:  用户名
     * @param password:  密码
     * @param tableName: a需要连接的表名
     * @return: 返回为FeatureCollection类型
     */
    private static SimpleFeatureCollection connAndgetCollection(String dbtype, String host, String port,
                                                                String database, String userName, String password, String tableName) {
        Map params = new HashMap();
        DataStore pgDatastore = null;
        params.put(PostgisNGDataStoreFactory.DBTYPE.key, dbtype); //需要连接何种数据库,postgis or mysql
        params.put(PostgisNGDataStoreFactory.HOST.key, host);//ip地址
        params.put(PostgisNGDataStoreFactory.PORT.key, new Integer(port));//端口号
        params.put(PostgisNGDataStoreFactory.DATABASE.key, database);//需要连接的数据库
        params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");//架构
        params.put(PostgisNGDataStoreFactory.USER.key, userName);//需要连接数据库的名称
        params.put(PostgisNGDataStoreFactory.PASSWD.key, password);//数据库的密码
        SimpleFeatureCollection fcollection = null;
        try {
            //获取存储空间
            pgDatastore = DataStoreFinder.getDataStore(params);
            //根据表名获取source
            SimpleFeatureSource fSource = pgDatastore.getFeatureSource(tableName);
            if (pgDatastore != null) {
                System.out.println("系统连接到位于:" + host + "的空间数据库" + database
                        + "成功!");
                fcollection = fSource.getFeatures();
            } else {
                System.out.println("系统连接到位于:" + host + "的空间数据库" + database
                        + "失败!请检查相关参数");

            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("系统连接到位于:" + host + "的空间数据库" + database
                    + "失败!请检查相关参数");
        }
        return fcollection;
    }

    public static void main(String[] args) {
        //调用方法
        SimpleFeatureCollection featureColls = PostGis.connAndgetCollection("postgis", "localhost", "5432", "beijing", "postgres", "123456", "planet_osm_point");
        SimpleFeatureIterator itertor = featureColls.features();
        //循环读取feature,itertor.hasNext()表示游标下一个是否有数据,有返回ture,否则为false
        while (itertor.hasNext()) {
            //获取每一个要素
            SimpleFeature feature = itertor.next();
            System.out.println(feature.getAttribute("planet_osm_point"));
        }

    }
}

注:数据库要导入空间数据,参考这篇文章https://blog.csdn.net/TcCookEgg/article/details/102496421

你可能感兴趣的:(空间数据库)