一、準(zhǔn)備工作
1.安裝PostgreSQL+PostGIS,版本不限(推薦最新版本)安裝教程:Windows上安裝、Linux上安裝。
2.osm2pgsql工具,下載地址。
3.安裝QGIS,方便查看數(shù)據(jù),下載地址。
二、具體步驟
1.windows安裝osm2pgsql
下載地址:Index of /download/windows (osm2pgsql.org)

windows版解壓即用:

2.下載OSM數(shù)據(jù)
1.下載全國數(shù)據(jù)量太大,以臺灣省為例;下載地址:http://download.geofabrik.de/asia.html,下載.osm.pbf格式數(shù)據(jù)。

2.將下載后的數(shù)據(jù)放在osm2pgsql根目錄下備用:

3.打開Postgres并創(chuàng)建數(shù)據(jù)庫
1.創(chuàng)建名為:taiwan數(shù)據(jù)庫

2.運(yùn)行sql給該數(shù)據(jù)庫添加擴(kuò)展:
CREATE EXTENSION postgis;
CREATE EXTENSION hstore;

4.osm2pgsql導(dǎo)入數(shù)據(jù)到postgres
1.為了避免輸入密碼報錯:ERROR: Cannot detect file format for 'XXXXX'. Try using -r
將postgres安裝目錄里的文件pg_hba.conf(文件路徑:...\PostgreSQL\版本號\data)里面的md5,下圖所示的兩個md5改為trust:

2.在osm2pgsql根目錄打開cmd,運(yùn)行命令:
osm2pgsql -s -U postgres -H 127.0.0.1 -P 5432 -d taiwan --hstore --style default.style --tag-transform style.lua --cache 12000 taiwan-latest.osm.pbf
注意:-U 用戶名 -W 密碼 -d 數(shù)據(jù)庫名,其他命名參考osm2pgsql常見命令。
3.等待導(dǎo)入完成:
md_665f32ad.png

5.查看數(shù)據(jù)
1.打開taiwan數(shù)據(jù)庫查看數(shù)據(jù)表:

| 表名 | 說明 |
|---|---|
| planet_osm_point | 點(diǎn)類型地理數(shù)據(jù)表 |
| planet_osm_line | 線類型地理數(shù)據(jù)表 |
| planet_osm_polygon | 面類型地理數(shù)據(jù)表 |
| planet_osm_roads | 路線地理數(shù)據(jù)表 |
所有圖層數(shù)據(jù)都在這四張表里面,nodes\rels\ways為導(dǎo)入過程生成的中間表,可以刪除。
2.使用QGIS連接Postgres數(shù)據(jù)庫查看數(shù)據(jù)

3.連接成功QGIS會顯示四個圖層:

4.添加圖層查看數(shù)據(jù):
planet_osm_line:

planet_osm_point:

planet_osm_polygon:

planet_osm_roads:

到此數(shù)據(jù)準(zhǔn)備完成,后面將對數(shù)據(jù)進(jìn)行查詢生成不同的地圖圖層。