Answer the question
In order to leave comments, you need to log in
How to make a prepopulated field in a django model?
There is a field in which the city is entered. Next, there are 2 fields with the coordinates of this city, latitude and longitude.
It is necessary to make it so that when entering a city, a request is sent to Google and coordinates are inserted from the answer.
I know how to make a request to Google, for example like this:
address = "Москва"
api_key = "api key google"
api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
api_response_dict = api_response.json()
if api_response_dict['status'] == 'OK':
lat = api_response_dict['results'][0]['geometry']['location']['lat']
lng = api_response_dict['results'][0]['geometry']['location']['lng']
Answer the question
In order to leave comments, you need to log in
You make a view that will send a request to Google
with Ajax you request it
Or you also request Google API directly with Ajax, and not from the server
as one of the OPTIONS:
1. In the model you make a method for obtaining coordinates (def get_gps ... return lat, lng)
2. pre_save signal ...instance. lat = ...
I decided this way:
- added, through the redefinition of the admin template, a button next to the city input field
- hung up the function of requesting coordinates:
(function($) { $(document).ready(function() {
$("#id_to_city").after('<input type="button" value="Запросить координаты" onclick="get_geo(el(\'id_to_city\').value)"/>');
});
})(django.jQuery);
function get_geo(city) {
var x = new XMLHttpRequest();
var api_key = "google_api_key";
var result = '';
x.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?address="+city+"&key="+api_key, true);
x.onload = function (){
result = JSON.parse(x.responseText);
el("id_to_lat").value = result.results[0].geometry.location.lat;
el("id_to_lng").value = result.results[0].geometry.location.lng;
};
x.send(null);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question