Django - Custom Geolocation
Currently developing a web application with Django 1.8 and wants to show city, country and zip code without being entered by user to register, can anyone please help me with this?
Thank.
+3
Josseline perdomo
source
to share
1 answer
You can implement this with HTML5 and Google Maps APIs.
- Using HTML5 Geolocation API , you will get the coordinates of the user's location.
- Using the coordinates and the Google Maps API for reverse geocoding , you will get the user's full address.
An example implementation -
function checkLocation() {
//geolocation API options
var options = {
maximumAge: 5 * 60 * 1000,
enableHighAccuracy: true,
timeout: 20000};
//success getting the geolocation
function success(ppos) {
lat = ppos.coords.latitude;
lng = ppos.coords.longitude;
codeLatLng(lat, lng);
}
//error when getting the geolocation
function error(err) {
var errorMessage = "Error:";
switch(err.code) {
case err.TIMEOUT:
errorMessage = 'Error: Attempts to retrieve location timed out.';
break;
case err.POSITION_UNAVAILABLE:
errorMessage = "Error: Your browser doesn't know where you are.";
break;
case err.PERMISSION_DENIED:
errorMessage = 'Error: You have to give us permission!';
break;
case err.UNKNOWN_ERROR:
errorMessage = 'Error: Unknown error returned.';
break;
default:
errorMessage = 'Error: ' + err + ' ' + err.code;
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options);
}
}
function codeLatLng(lat, lng) {
var lat = parseFloat(lat);
var lng = parseFloat(lng);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
return results[1].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
I think this solution might give you the country and city, but I don't think it will give you the zip code.
+3
Emad mokhtar
source
to share