【问题标题】:How to use google maps api to get user location in django?如何使用谷歌地图 api 在 django 中获取用户位置?
【发布时间】:2018-12-05 18:09:23
【问题描述】:

我正在做一个 django 项目,需要获取用户位置,我尝试的是用户可以手动输入他的城市或单击定位按钮,该按钮将自动找到其位置并填充城市。

我试过GeoIP但还不够,谷歌地图api可以吗?

如果不是,那么某些网站如何自动填写我的位置,例如电影票预订、酒店预订网站?

如果你能告诉我我想要实现的可行解决方案是什么?

【问题讨论】:

  • 我想你可以在那里找到你要找的东西:stackoverflow.com/questions/2218093/django-retrieve-ip-location
  • @SergeyPugach 感谢您的回复,但如前所述,GeoIp 不足以满足我的工作,还有其他建议吗?
  • @PankajSharma 你找到解决方案了吗?我刚刚开始使用 Django,所以我可能会遗漏一些东西,但实际上没有文档,也没有关于如何完成它的教程。
  • @CollinsOrlando 我已经发布了我使用的答案,希望对您有所帮助:)

标签: django python-3.x google-maps google-maps-api-3 gps


【解决方案1】:

我使用GeoLocation 获取经度和纬度,然后使用 google api 获取街道地址、城市、州、国家等。

这是我使用的代码 -

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {

         let lat = position.coords.latitude;
         let long = position.coords.longitude;
         $("input[name='lat']").val(lat);
         $("input[name='lat']").val(long);
         let url_str = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&key=yourkey'
        $.getJSON(url_str, function(data) {
              console.log(data);
              //here you get the location data, like street address, city and pass it to inputs and submit the form to save it.
          });
        }

【讨论】:

  • 如何在DataBase中保存位置?
  • @Pankaj ,我如何将位置保存在数据库中?
  • @Smith 你有latitudelongitudeaddress 在客户端,你可以使用ajax 将它们直接传递给django 视图,也可以用于自动填充表单并让用户编辑和提交表单。
猜你喜欢
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多