如何解决将经度和纬度保存到 Django 中的用户配置文件
我一直在寻找一种使用 HTML5(可能还有 JS)将访问者/用户纵向和纬度数据保存到数据库的方法。我不希望使用包,因为它们看起来有点过时,并且考虑到它们对其他 API 的依赖,将来可能会破坏我的代码。
我知道有一种使用 AJAX 的方法,但我显然不知道和理解它以实现它。
我对学过的领主的要求是 - 1. 获取 Loc 数据 2. 以 dict 或 json 或字符串格式将其发送到 Python,从中可以进一步处理和保存。
为什么你会问 - 好问题。我会用它来显示主页上的天气和“登录”页面上的本地 Twitter 趋势。
如有任何帮助,我们将不胜感激。
干杯!
我的JS代码如下:
// Set up global variable
var result;
function showPosition() {
// Store the element where the page displays the result
result = document.getElementById("result");
// If geolocation is available,try to get the visitor's position
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback,errorCallback);
result.innerHTML = "Getting the position information...";
} else {
alert("Sorry,your browser does not support HTML5 geolocation.");
}
};
// Define callback function for successful attempt
function successCallback(position) {
result.innerHTML = [position.coords.latitude,position.coords.longitude];
}
// Define callback function for failed attempt
function errorCallback(error) {
if (error.code == 1) {
result.innerHTML = "You've decided not to share your position,but it's OK. We won't ask you again.";
} else if (error.code == 2) {
result.innerHTML = "The network is down or the positioning service can't be reached.";
} else if (error.code == 3) {
result.innerHTML = "The attempt timed out before it could get the location data.";
} else {
result.innerHTML = "Geolocation failed due to unknown error.";
}
}
window.onload = showPosition;
解决方法
什么对我有用:
首先,我建议您在模型上使用 models.PointField
。
当我在 FE 上获取 long/lat 数据时,我以以下格式将其作为表单数据发送,例如:
"{\"type\":\"Point\",\"coordinates\":[14.215641,50.0100000001]}"
然后我将其映射到模型字段并保存。它保存得很好,后来我可以用它查询谷歌地理编码器或任何东西。
,在您的 JS 代码中:
function successCallback(position) {
result.innerHTML = [position.coords.latitude,position.coords.longitude];
$.post('your-python-endpoint-url',{
latitude: position.coords.latitude,longitude: position.coords.longitude
});
}
在你的蟒蛇中:
def index(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.body
return HttpResponse("OK")
根据需要更改方法名和正文,不要忘记在django中定义路由。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。