LoginSignup
0
1

More than 1 year has passed since last update.

IPアドレスからおおよその場所(緯度経度)を取得する

Last updated at Posted at 2022-06-30

gecoderを使う方法

install

pip install geocoder

中を見るとWebサービスを利用しているから、オンラインアクセスが出来ないと駄目だったり、Webサービスがなんらかで中断してたら使えない。

code

codeはこんな感じ

import geocoder

def ip2geocode(ip):
    g = geocoder.ip(ip)
    if len(g.latlng) == 0:
        print('IPから位置情報が取れない IP={0}'.format(ip))
    else:
        print('latlng = {0},{1}'.format(g.latlng[0], g.latlng[1]))
        print('https://www.google.com/maps?q={0},{1}'.format(g.latlng[0], g.latlng[1]))

GeoLite2を使う場合

DBのダウンロード

ここからDBをダウンロードする必要がある。

GeoLite2 Free Geolocation Data

GeoLite2 CityのGZIPをダウンロードする。

でも、サインインしないと駄目。ライセンス契約をみると、ちゃんと使っていることに対してドキュメントに書かないといけない。
The GeoLite2 end-user license agreement incorporates components of the Creative Commons Attribution-ShareAlike 4.0 International License. The attribution requirement may be met by including the following in all advertising and documentation mentioning features of or use of GeoLite2 data:

ちゃんと書いているから違反してないはずなんだけど、ドキドキしちゃう。

インストール

pip install geoip2

code

import geoip2.database

def ip2geoLite2(ip):
    reader = geoip2.database.Reader('GeoLite2-City.mmdb')
    response = reader.city(ip)
    print('latlng = {0},{1}'.format(response.location.latitude, response.location.longitude))
    print('https://www.google.com/maps?q={0},{1}'.format(response.location.latitude, response.location.longitude))

DBが約62MBあるけど、こちらはオフラインで出来る。

こんな感じで並べて調査してみる。

import sys
import geocoder
import geoip2.database

def ip2geocode(ip):
    g = geocoder.ip(ip)
    if len(g.latlng) == 0:
        print('IPから位置情報が取れない IP={0}'.format(ip))
    else:
        print('latlng = {0},{1}'.format(g.latlng[0], g.latlng[1]))
        print('https://www.google.com/maps?q={0},{1}'.format(g.latlng[0], g.latlng[1]))

def ip2geoLite2(ip):
    reader = geoip2.database.Reader('GeoLite2-City.mmdb')
    response = reader.city(ip)
    print('latlng = {0},{1}'.format(response.location.latitude, response.location.longitude))
    print('https://www.google.com/maps?q={0},{1}'.format(g.latlng[0], g.latlng[1]))

if __name__ == '__main__':
    args = sys.argv
    if 2 <= len(args):
        if args[1].isascii:
            ip = args[1]
    print('ip = {0}'.format(ip))
    ip2geocode(ip)
    ip2geoLite2(ip)

結果が物凄く差がでる。

たまたまなのかもしれないのですが、geocoderの方は日本のIPアドレスは、ほとんどが東京都庁になる。関西の方のIPアドレスでも東京都庁になる。
アクセスしている国の判定に使う感じなのかな。

参考

0
1
0

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
0
1