geotools連接PostgreSQL數(shù)據(jù)庫

geotools快速入門

GeoTools是一個(gè)開放源代碼(LGPL)Java代碼庫,它提供了符合標(biāo)準(zhǔn)的方法來處理地理空間數(shù)據(jù),例如實(shí)現(xiàn)地理信息系統(tǒng)(GIS)豆拨。

步驟

參照官網(wǎng):https://geotools.org/

QuickStart

我使用的是idea
選擇IDE

其實(shí)我創(chuàng)建的時(shí)候并不是按照官網(wǎng)上的步驟來的,因?yàn)槲冶容^習(xí)慣從https://start.spring.io/
上面構(gòu)建一個(gè)新的maven項(xiàng)目,填寫命名下載壓縮包产还,然后在idea中打開。
pom中增加依賴包:

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <geotools.version>24-SNAPSHOT</geotools.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
    </dependencies>
    <repositories>
      <repository>
        <id>osgeo</id>
        <name>OSGeo Release Repository</name>
        <url>https://repo.osgeo.org/repository/release/</url>
        <snapshots><enabled>false</enabled></snapshots>
        <releases><enabled>true</enabled></releases>
      </repository>
      <repository>
        <id>osgeo-snapshot</id>
        <name>OSGeo Snapshot Repository</name>
        <url>https://repo.osgeo.org/repository/snapshot/</url>
        <snapshots><enabled>true</enabled></snapshots>
        <releases><enabled>false</enabled></releases>
      </repository>
    </repositories>

測試一下

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

運(yùn)行嘀趟,打開shp文件


打開文件

效果

連接PostgreSQL數(shù)據(jù)庫

在網(wǎng)上找到geotools連接數(shù)據(jù)庫的資料脐区,
參考:https://www.cnblogs.com/tuboshu/p/10752286.html
但是發(fā)現(xiàn)導(dǎo)入依賴失敗

導(dǎo)入依賴失敗

最后看到這個(gè):http://www.reibang.com/p/e04f486b7954
但是還是失敗了,經(jīng)過多次嘗試她按,終于找到正確的依賴包牛隅。

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <geotools.version>24-SNAPSHOT</geotools.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-hsql</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <!-- Provides support for PostGIS. Note the different groupId -->
        <dependency>
            <groupId>org.geotools.jdbc</groupId>
            <artifactId>gt-jdbc-postgis</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
<repositories>
        <repository>
            <id>osgeo</id>
            <name>OSGeo Release Repository</name>
            <url>https://repo.osgeo.org/repository/release/</url>
            <snapshots><enabled>false</enabled></snapshots>
            <releases><enabled>true</enabled></releases>
        </repository>
        <repository>
            <id>osgeo-snapshot</id>
            <name>OSGeo Snapshot Repository</name>
            <url>https://repo.osgeo.org/repository/snapshot/</url>
            <snapshots><enabled>true</enabled></snapshots>
            <releases><enabled>false</enabled></releases>
        </repository>
        <repository>
            <id>maven2-repository.dev.java.net</id>
            <name>Java.net repository</name>
            <url>http://download.java.net/maven/2</url>
        </repository>
    </repositories>
成功

接下來就是上代碼:

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: 連接數(shù)據(jù)庫
 * @author: zhudan
 * @create: 2020/6/18 18:45
 */
public class PostGis {
    /**
     * @param dbtype:    數(shù)據(jù)庫類型,postgis or mysql
     * @param host:      ip地址
     * @param port:      端口號(hào)
     * @param database:  需要連接的數(shù)據(jù)庫
     * @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<String, Object> params = new HashMap<String, Object>();
        DataStore pgDatastore = null;
        params.put(PostgisNGDataStoreFactory.DBTYPE.key, dbtype); //需要連接何種數(shù)據(jù)庫酌泰,postgis or mysql
        params.put(PostgisNGDataStoreFactory.HOST.key, host);//ip地址
        params.put(PostgisNGDataStoreFactory.PORT.key, new Integer(port));//端口號(hào)
        params.put(PostgisNGDataStoreFactory.DATABASE.key, database);//需要連接的數(shù)據(jù)庫
        params.put(PostgisNGDataStoreFactory.SCHEMA.key, "public");//架構(gòu)
        params.put(PostgisNGDataStoreFactory.USER.key, userName);//需要連接數(shù)據(jù)庫的名稱
        params.put(PostgisNGDataStoreFactory.PASSWD.key, password);//數(shù)據(jù)庫的密碼
        SimpleFeatureCollection fcollection = null;
        try {
            //獲取存儲(chǔ)空間
            pgDatastore = DataStoreFinder.getDataStore(params);
            //根據(jù)表名獲取source
            SimpleFeatureSource fSource = pgDatastore.getFeatureSource(tableName);
            if (pgDatastore != null) {
                System.out.println("系統(tǒng)連接到位于:" + host + "的空間數(shù)據(jù)庫" + database
                        + "成功媒佣!");
                fcollection = fSource.getFeatures();
            } else {
                System.out.println("系統(tǒng)連接到位于:" + host + "的空間數(shù)據(jù)庫" + database
                        + "失敗陵刹!請(qǐng)檢查相關(guān)參數(shù)");

            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("系統(tǒng)連接到位于:" + host + "的空間數(shù)據(jù)庫" + database
                    + "失斈椤!請(qǐng)檢查相關(guān)參數(shù)");
        }
        return fcollection;
    }

    public static void main(String[] args) {
        //調(diào)用方法
        SimpleFeatureCollection featureColls = PostGis.connAndgetCollection("postgis", "localhost", "5432", "beijing", "postgres", "123456", "planet_osm_point");
        SimpleFeatureIterator itertor = featureColls.features();
        //循環(huán)讀取feature衰琐,itertor.hasNext()表示游標(biāo)下一個(gè)是否有數(shù)據(jù)也糊,有返回ture,否則為false
        while (itertor.hasNext()) {
            //獲取每一個(gè)要素
            SimpleFeature feature = itertor.next();
            System.out.println(feature.getAttribute("planet_osm_point"));
        }

    }
}

注:數(shù)據(jù)庫要導(dǎo)入空間數(shù)據(jù),參考這篇文章https://blog.csdn.net/TcCookEgg/article/details/102496421

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末碘耳,一起剝皮案震驚了整個(gè)濱河市显设,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌辛辨,老刑警劉巖捕捂,帶你破解...
    沈念sama閱讀 216,744評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瑟枫,死亡現(xiàn)場離奇詭異,居然都是意外死亡指攒,警方通過查閱死者的電腦和手機(jī)慷妙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來允悦,“玉大人膝擂,你說我怎么就攤上這事∠冻冢” “怎么了架馋?”我有些...
    開封第一講書人閱讀 163,105評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長全闷。 經(jīng)常有香客問我叉寂,道長,這世上最難降的妖魔是什么总珠? 我笑而不...
    開封第一講書人閱讀 58,242評(píng)論 1 292
  • 正文 為了忘掉前任屏鳍,我火速辦了婚禮,結(jié)果婚禮上局服,老公的妹妹穿的比我還像新娘钓瞭。我一直安慰自己,他們只是感情好淫奔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,269評(píng)論 6 389
  • 文/花漫 我一把揭開白布山涡。 她就那樣靜靜地躺著,像睡著了一般搏讶。 火紅的嫁衣襯著肌膚如雪佳鳖。 梳的紋絲不亂的頭發(fā)上霍殴,一...
    開封第一講書人閱讀 51,215評(píng)論 1 299
  • 那天媒惕,我揣著相機(jī)與錄音,去河邊找鬼来庭。 笑死妒蔚,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的月弛。 我是一名探鬼主播肴盏,決...
    沈念sama閱讀 40,096評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼帽衙!你這毒婦竟也來了菜皂?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,939評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤厉萝,失蹤者是張志新(化名)和其女友劉穎恍飘,沒想到半個(gè)月后榨崩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,354評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡章母,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,573評(píng)論 2 333
  • 正文 我和宋清朗相戀三年母蛛,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片乳怎。...
    茶點(diǎn)故事閱讀 39,745評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡彩郊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蚪缀,到底是詐尸還是另有隱情秫逝,我是刑警寧澤,帶...
    沈念sama閱讀 35,448評(píng)論 5 344
  • 正文 年R本政府宣布询枚,位于F島的核電站筷登,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏哩盲。R本人自食惡果不足惜前方,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,048評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望廉油。 院中可真熱鬧惠险,春花似錦、人聲如沸抒线。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嘶炭。三九已至抱慌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間眨猎,已是汗流浹背抑进。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留睡陪,地道東北人寺渗。 一個(gè)月前我還...
    沈念sama閱讀 47,776評(píng)論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像兰迫,于是被迫代替她去往敵國和親信殊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,652評(píng)論 2 354