我正在尝试获取用户设备的位置。但geoip2返回的位置远离用户位置(几乎20 the 25 the)。当我通过移动网络连接我的设备时,当我将我的设备连接到wifi时,它会显示一个不同的位置
首先,我要获取用户的ip
def get_ip(request):
xff = request.META.get('HTTP_X_FORWARDED_FOR')
if xff:
ip = xff.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR', None)
return ip但是这会得到用户的私有ip,而私有ip不在国家或城市数据集中,因此geoip2会抛出一个错误。
所以我试着通过网站获取公共ip地址
def get_ip(request):
from requests import get
ip = get('https://api.ipify.org').text
if ip:
return ip现在我使用geoip2来获取用户的位置数据
def home(request,):
....
....
....
....
from django.contrib.gis.geoip2 import GeoIP2
g = GeoIP2()
ip = get_ip(request)
print(ip)
country = g.country(ip)
city = g.city(ip)
print(country, city)
lat, long = g.lat_lon(ip)
print(lat, long)
...
...
...你能建议一种更好的方法或适当的方法来获得用户的准确位置吗?
发布于 2020-11-08 15:15:53
首先,您需要了解geoip2使用.dat/csv文件,这些文件只不过是包含根据国家/城市/纬度-经度的IP地址范围的文件。这些文件需要及时更新,以获得更准确的数据。其次,如果您使用localhost执行此操作,则第一个代码将返回这个127.0.0.1IP地址,因为您正在获取远程IP。
def home(request):
xff = request.META.get('HTTP_X_FORWARDED_FOR')
if xff:
ip = xff.split(',')[0]
country = g.country(ip)
city = g.city(ip)
lat, long = g.lat_lon(ip)
else:
ip = request.META.get('REMOTE_ADDR', None)
country = 'Your Country Name'
city='Your City'
lat,long = 'Your Latitude','Your Longitiude'
print(country, city)
print(lat, long)此代码也适用于本地主机,因此您不会收到IP错误。要获得准确的位置,请更新您的dat/csv文件
https://stackoverflow.com/questions/64735522
复制相似问题