LoginSignup
476

More than 5 years have passed since last update.

国土交通省のデータを使って、緯度経度から市区町村までを取り出す

Posted at

FrogApps 技術ブログ始めました!
RailsやiOS、HTML5の情報を発信中!! → http://qiita.com/teams/frogapps


ここ数年、位置情報を使ったアプリ・サービスが増えましたが、GPSから取得出来る緯度経度だけではデータとして使いにくい事があります。

GoogleのGeocodingサービスなどで、緯度経度から住所への変換ができますが、件数や速度の問題があります。

そこで、国土交通省のデータを元に、緯度経度から住所への変換を行ってみましょう。

国土数値情報ダウンロードサービス

から全都道府県を選択。最新の情報を全都道府県分選択します。

PostGISのセットアップ

http://trac.osgeo.org/postgis/wiki/UsersWikiPostGIS20Ubuntu1204 を参考にPostGISをインストールしてください。

sudo -u postgres psql template1
CREATE USER vagrant WITH PASSWORD 'vagrant';
CREATE DATABASE gis WITH ENCODING = 'UTF-8'
    LC_CTYPE = 'en_US.utf8' LC_COLLATE = 'en_US.utf8'
    TEMPLATE template0;
GRANT ALL PRIVILEGES ON DATABASE gis TO vagrant;

sudo -u postgres psql gis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/postgis.sql
sudo -u postgres psql gis -f /usr/share/postgresql/9.1/contrib/postgis-2.0/spatial_ref_sys.sql 

shpファイルからPostGISへ取り込み

sudo aptitude install unzip nkf

# すべてのZIPファイルを解凍
find ./ -name "*.zip" -type f -print0 | xargs -0 -I {} unzip {}

# shpファイルからSQLへ変換
shp2pgsql -c N03-13_01_130401.shp shapes > geo.sql
find ./ -name "*.shp" -type f -print0 | xargs -0 -I {} shp2pgsql -W "SHIFT-JIS" -a {} shapes | nkf -W >> geo.sql

# 取り込み
psql gis < geo.sql 

検索

時計台の位置情報

psql gis

SET client_encoding = 'UTF8';
SELECT n03_001,n03_002,n03_003,n03_004 FROM shapes WHERE ST_Within(ST_GeomFromText('POINT(141.35358861111  43.062555)'), geom);

 n03_001 | n03_002 | n03_003 | n03_004 
---------+---------+---------+---------
 北海道  |         | 札幌市  | 中央区

テーブルへ変換

PostGISを使えば比較的簡単にできるのですが、変換の為にProduction環境にPostGISを配置するのは面倒です。

なので、先に緯度経度から行政区の変換マップを作りました。
https://github.com/FrogAppsDev/jpcities からダウンロードしてください。

検索がしやすいようにGeohashでインデックスしています。精度は荒いですが大体の位置を把握するには役にたつと思います。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
476