Javascript:启用高精度地理位置

时间:2018-08-17 02:51:59

标签: javascript django html5 geolocation

如何通过在代码中添加“启用高精度”属性来改善地理位置?我是一个初学者,还在学习Javascript。如果有人可以帮助我,我将不胜感激。谢谢。

script.js

var pos;

var $demo;

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 5000,
};

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, options);
  } else {
    $demo.text("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  pos = position;
  var { latitude, longitude } = pos.coords;
  $demo.html(`Latitude: ${latitude}<br>Longitude: ${longitude}`);
  $('#btn_submit').attr("disabled", null);
}

$(document).ready(function() {
  $demo = $("#demo");
  $('#btn_submit').on('click', function() {
    var data = pos.coords;
    data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
    $.post("/ajax/insert", data, function() {
      alert("Saved Data!");
    });
  });
});

index.html

{% extends 'ajax/base.html' %}
{% block body %}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Your Location</button>
<p id="demo"></p>
<button type="button" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button>
{% endblock %}

views.py

from django.http import JsonResponse
from .models import Member
def insert(request):
    if request.method == 'POST':
        member = Member(latitude=request.POST['latitude'], longitude=request.POST['longitude'])
        member.save()
        return JsonResponse({'message': 'success'})

0 个答案:

没有答案