I’m trying to load my home page according to the geolocation given by the browser, if the coordinates are ok, I load a list of airports around these coordinates, otherwise I load all airports.
However, I can’t manage this between GET & POST requests. Each time I get all the airports in the page.
In fact when the view is loaded (by the GET request) all airport are displayed, after when the page is entirely loaded the POST event is raised with the GPS information. So the list of airports around location is performed but the rendering is always wrong.
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home_view),
views.py
def home_view(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
if request.method == 'POST':
Latitude = float(request.POST.get('latitude'))
Longitude = float(request.POST.get('longitude'))
context = aviationweatherapi.getStationInfo(Latitude,Longitude)
print ("Get airports list around current GPS location")
else:
#The request is GET
context = aviationweatherapi.getStationInfo(None, None)
print ("Get all airports")
context.update({'IP':ip})
return render(request,'acceuil.html',context)
template_Base.html (base of the acceuil.html)
<body>
{% csrf_token %}
{% block contenu %} {% endblock %}
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
const findLoc = () => {
const success = (position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
var data = {'latitude': latitude,
'longitude': longitude };
data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
console.log('Location is on');
console.log(data);
document.getElementById("LocationLat").innerHTML = latitude;
document.getElementById("LocationLon").innerHTML = longitude;
$.post("/", data);
}
const error = () => {
console.log('Location gathering Not allowed')
const latitude = 0 // Default Latitude
const longitude = 0 // Default Longtitude
var data = {'latitude': latitude,
'longitude': longitude,
};
data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
console.log(data);
document.getElementById("LocationLat").innerHTML = "err.latitude";
document.getElementById("LocationLon").innerHTML = "err.longitude";
$.post("/", data);
}
navigator.geolocation.getCurrentPosition(success,error);
}
// Location is fetched when user loads screen
Window.onload = findLoc();
</script>
Heavy PC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.