I was looking for a way to use HTML5 (and possibly JS) to save visitor/user Longitudnal & Latitudnal data to a database. I do not wish to use packages out there as they seem a bit outdated and may break my code in future considerting their own reliance on other APIs.
I know there is a way around using AJAX, but I clearly dont know and understand it well enough to implement it.
My ask of the learned Lords is – 1. Get Loc data 2. Send it to Python in dict or json or string format from where it can be further processed and saved.
Why you may ask – Good question. I would use it for displaying weather on the homepage and local twitter trends on a ‘logged-in’ page.
Any assistance would be appreciated.
Cheers!
My JS code is below:
// 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;
2
Answers
In your JS code:
In your python:
Change the method name and body according to your needs and don’t forget to define a route in django.
what works for me:
First I recommend you to use
models.PointField
on your model.When I obtain the long/lat data on FE, I send it as form-data in the following format eg:
Then I map it to the model field and save it. It saves well and later I am able to query google geocoder or anything with it.