【问题标题】:Django - User GeolocationDjango - 用户地理位置
【发布时间】:2015-07-12 07:39:06
【问题描述】:

目前正在使用 Django 1.8 开发一个 Web 应用程序,并且希望能够显示城市、国家和邮政编码,而无需用户输入注册,请有人帮助我吗?

谢谢。

【问题讨论】:

  • 查看GeoDjango,使用GeoIP link
  • 我尝试使用 GeoIP 但不适用于私有 IP @Pynchia
  • 当然不是! ;D
  • 好吧,我试着找到一个更通用的解决方案@Pynchia
  • 如果你找到了请告诉我!!

标签: python django geolocation


【解决方案1】:

您可以使用 HTML5 和 Google Maps API 来实现这一点。

  1. 使用HTML5 Geolocation APIs,您将获得用户的位置坐标。
  2. 使用坐标和Google Maps API for reverse geocoding,您将获得用户的完整地址。

示例实现-

function checkLocation() {
    //geolocation API options
    var options =  {
        maximumAge: 5 * 60 * 1000,
        enableHighAccuracy: true,
        timeout: 20000};
    //success getting the geolocation
    function success(ppos) {
        lat = ppos.coords.latitude;
        lng = ppos.coords.longitude;
        codeLatLng(lat, lng);
    }
    //error when getting the geolocation 
    function error(err) {
        var errorMessage = "Error:";
        switch(err.code) {
            case err.TIMEOUT:
            errorMessage = 'Error: Attempts to retrieve location timed out.';
            break;
            case err.POSITION_UNAVAILABLE:
            errorMessage = "Error: Your browser doesn't know where you are.";
            break;
            case err.PERMISSION_DENIED:
            errorMessage = 'Error: You have to give us permission!';
            break;
            case err.UNKNOWN_ERROR:
            errorMessage = 'Error: Unknown error returned.';
            break;
            default:
            errorMessage = 'Error: ' + err + ' ' + err.code;
        }
    }
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error, options);
    }
}

function codeLatLng(lat, lng) {
    var lat = parseFloat(lat);
    var lng = parseFloat(lng);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                return results[1].formatted_address;
            } else {
                alert('No results found');
            }
        } else {
            alert('Geocoder failed due to: ' + status);
        }
    });
}

我认为此解决方案可以为您提供国家和城市,但我认为它不会为您提供邮政编码。

【讨论】:

  • 它也可以提供邮政编码,但仅限于可用的地方。大多数国家都是这样。使用 Google Geolocation API 的两个缺点是 1. 用户必须同意与您共享位置;以及 2. 在命名方面存在某种不一致。地区、次地区、行政区域级别_X 对不同的国家有不同的含义。它需要一些思考和反复试验才能保持一致性。
  • 如何在DataBase中保存位置?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2011-06-14
相关资源
最近更新 更多