Django http response code 500 error - javascript

I'm trying to order a bunch of coordinates by their distance to another input coordinate. Whenever I try to order, I get the error code 500. Any ideas?
Here's an image of the response codes and I circled the error code associated with my GET request.
Here's the Javascript in the Django template:
function searchWaypoints() {
geocoder.geocode({
'address': $('#address').val()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
$.get("{% url 'waypoints-search' %}", {
lat: position.lat(),
lng: position.lng()
}, function (data) {
if (data.isOk) {
$('#waypoints').html(data.content);
waypointByID = data.waypointByID;
activateWaypoints();
} else {
alert(data.message);
}
}, 'json');
} else {
alert('Could not find geocoordinates for the following reason: ' + status);
}
});
}
$('#searchWaypoints').click(searchWaypoints);
$('#address').keydown(function(e) {
if (e.keyCode == 13) searchWaypoints();
});
Here's the urls.py"
urlpatterns = patterns('waypoints.views',
url(r'^$', 'index', name='waypoints-index'),
url(r'^save$', 'save', name='waypoints-save'),
url(r'^search$', 'search', name='waypoints-search'),
)
Here's the view in views.py:
def search(request):
'Search waypoints'
# Build searchPoint
try:
searchPoint = Point(float(request.GET.get('lng')), float(request.GET.get('lat')))
except:
return HttpResponse(simplejson.dumps(dict(isOk=0, message='Could not parse search point')))
# Search database
waypoints = Waypoint.objects.distance(searchPoint).order_by('distance')
# Return
return HttpResponse(simplejson.dumps(dict(
isOk=1,
content=render_to_string('waypoints/waypoints.html', {
'waypoints': waypoints
}),
waypointByID=dict((x.id, {
'name': x.name,
'lat': x.geometry.y,
'lng': x.geometry.x,
}) for x in waypoints),
)), mimetype='application/json')

Change mimetype='application/json' to content_type="application/json"
or you can just use JsonResponse in Django
https://docs.djangoproject.com/en/1.8/ref/request-response/#jsonresponse-objects

Related

Handling Google Geocode Callback Results to Vue JS Model

Here's my issue... I have two selections for my user, use current location, or use a zip code. When the user selects a zip code I make a call to the Google geocode API and retrieve the central point for that zip code. I want to be able to put these coordinates into my Vue model and then execute a method within Vue called refresh which retrieves some data from my database and calls a function that sets up the map with markers and bounds. Since the callback function is decoupled from the model, I cannot seem to set the Vue properties, nor can I call the method. How do I handle the callback?
Please note that the refresh method works properly when using the selection for current location.
getLocation is called when the user selects "Current Location"
checkZip is called when the user selects "Use Zip Code"
<script>
var app = new Vue({
el: '#app-content',
data: {
locationType: "CurrentLocation",
lat: "",
lng: "",
radiusInMiles: 10,
filters: [],
zipCode: "",
geoError: "",
error: "",
results: []
},
methods: {
getLocation: function () {
this.zipCode = "";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.storeLocation, this.locationError);
} else {
this.locationType = "ZipLocation";
console.log("Geolocation does not appear to be supported by the browser.");
this.geoError = "Unable to obtain location. Please make sure location services are turned on and try again.";
}
},
storeLocation: function (position) {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.refresh();
},
locationError: function (err) {
this.locationType = "ZipLocation";
this.results = [];
console.warn(err);
this.geoError = "Unable to obtain location. Please make sure location services are turned on and try again.";
},
refresh: function () {
if (!(this.lat && this.lng && this.radiusInMiles && this.filters)) {
console.log("Location and filters are undefined.");
}
else {
//https://github.com/axios/axios
axios
.post('xyxyxyxyx', {
lat: this.lat,
lng: this.lng,
radiusInMiles: this.radiusInMiles,
filters: this.filters.toString()
})
.then(response => {
this.results = response.data.d;
//Send to map function...
loadMap(this.lat, this.lng, this.results);
})
.catch (error => console.log(error))
}
},
checkZip: function () {
if (this.zipCode.length == 5 && !isNaN(this.zipCode)) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'zipcode ' + this.zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Here's my issue...
//How do I store to the model and then call this.refresh
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
this.refresh();
} else {
console.error("Request failed.")
}
});
}
}
}
})
</script>
I was able to get this to work by copying the Vue model into a variable (self).
How can I update a Vue app's or component's property in a promise call back?
checkZip: function () {
if (this.zipCode.length == 5 && !isNaN(this.zipCode)) {
var self = this;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'zipcode ' + this.zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.lat = results[0].geometry.location.lat();
self.lng = results[0].geometry.location.lng();
self.refresh();
} else {
console.error("Request failed.")
}
});
}
}

Is there a way to display console data in HTML with an onclick?

I want to display console data on my localhost whenever a button is clicked. How would I display such data on my website? When I click the button, I see the data in the console and all I need now is for the actual data to be visualized in a grid view or similar.
I'm rather new to this, hence why I'm here.
function ipLookUp () {
$.ajax('http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
getAddress(response.lat, response.lon)
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
function getAddress (latitude, longitude) {
// $.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=AIzaSyAq3EWvKjpBxwlovWzvnH5xj9zXVk9_C10')
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' +longitude + '&key=AIzaSyAq3EWvKjpBxwlovWzvnH5xj9zXVk9_C10')
.then(
function success (response) {
console.log('User\'s Address Data is ', response)
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
getAddress(position.coords.latitude,
position.coords.longitude)
},
function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving location', error_message)
ipLookUp()
});
}
else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}
The output in the console looks like this:
{status: "success", country: "Sweden", countryCode: "SE", region: "E", regionName: "Östergötland", …}
as: "AS205016 HERN Labs AB"
city: "Linköping"
country: "Sweden"
countryCode: "SE"
isp: "HERN Labs AB"
lat: 58.4116
lon: 15.6268
org: ""
query: "77.111.247.148"
region: "E"
regionName: "Östergötland"
status: "success"
timezone: "Europe/Stockholm"
zip: "582 22"
Try to create HTML elements and define IDs for easier access through selectors (getElementById for example).
<html>
<body>
<p id="coords"></p>
<p id="country"></p>
<p id="address"></p>
</body>
</html>
Then you can access the element and update it:
function getAddress (latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' +longitude + '&key=KEY')
.then(
function success (response) {
document.getElementById('address').innerHTML = 'User\'s Address Data is ' + response;
},
function fail (status) {
console.log('Request failed. Returned status of',
status)
}
)
}
Hopes this helps you ! you can read more about Javascript from MDN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body onload="fetchCurrentLocation()">
<div id="list"></div>
<script>
function renderList(response) {
let ul = document.createElement('ul');
if (response.status === "OK ") {
let list = response.results;
for (let index = 0; index < list.length; index++) {
let item = list[index];
let li = document.createElement('li');
li.innerHTML = `<span> ${item.formatted_address} </span>`;
ul.appendChild(li);
}
} else {
let li = document.createElement('li');
li.innerHTML = `<span> Something goes wrong </span>`;
ul.appendChild(li);
}
document.getElementById('list').appendChild(ul);
}
function ipLookUp(params) {
$.ajax('http://ip-api.com/json')
.then(
function success(response) {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country', response.country);
getAddress(response.lat, response.lon)
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);
}
function getAddress(latitude, longitude) {
$.ajax('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&key=AIzaSyAq3EWvKjpBxwlovWzvnH5xj9zXVk9_C10')
.then(
function success(response) {
console.log('User\'s Address Data is ', response)
renderList(response);
},
function fail(status) {
renderList(response);
console.log('Request failed. Returned status of', status)
}
)
}
function fetchCurrentLocation() {
if ("geolocation" in navigator) {
// check if geolocation is supported/enabled on current browser
navigator.geolocation.getCurrentPosition(
function success(position) {
// for when getting location is a success
console.log('latitude', position.coords.latitude,
'longitude', position.coords.longitude);
getAddress(position.coords.latitude,
position.coords.longitude)
},
function error(error_message) {
// for when getting location results in an error
console.error('An error has occured while retrieving location', error_message)
ipLookUp()
});
}
else {
// geolocation is not supported
// get your location some other way
console.log('geolocation is not enabled on this browser')
ipLookUp()
}
}
</script>
</body>
</html>

GoogleMaps API latitude and longitude returned differently

I use the googleMaps API to get location data from a given address:
function geocodeAddress(address, callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: address }, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results.length > 0) {
callback(results[0].geometry.location);
} else {
console.log("No results found");
}
} else {
console.log("Geocoder failed due to: " + status);
}
});
}
function getLatLng(address, callback) {
latLng = [];
geocodeAddress(address, function(position) {
latLng.push(position.lat());
latLng.push(position.lng());
callback(latLng);
});
}
// Search for address provided by user via Google Maps API
setMapToSearchAddress: function() {
var vm = this;
// Set the location in map to the address given
setMapLocationToAddress(this.searchAddress);
getLatLng(this.searchAddress, function(latlng) {
console.log(latlng);
vm.latitude = latlng[0];
vm.longitude = latlng[1];
})
}
But when I send a POST request to my server and print the output of the request being sent, I see, that the longitude is sent as a number, whereas the latitude is sent as a string. But I never converted the data?
function postDataToServer(endpoint, data, callback) {
$.post("v1/".concat(endpoint), function(data, response) {
callback(response);
})
}
createIncident: function() {
var incidentData = {
"incidentReference": "",
"latitude": this.latitude,
"longitude": this.longitude,
"streetName": this.address,
"featureTypeId": 1,
"archived": 0
}
console.log(incidentData);
// POST data to server
postDataToServer("incidents", incidentData, function(response) {
console.log(response);
})
},
Object {incidentReference: "", latitude: "48.15312", longitude:
11.583509999999933, streetName: "Leopoldstraße 8", featureTypeId: 1…}archived: 0featureTypeId: 1incidentReference: ""latitude:
"48.15312"longitude: 11.583509999999933streetName: "Leopoldstraße 8"
Why are these variables treated differently?

Angular JS service sending coordinates to controller

My app needs to get a path ( list of latitude and longitudes )in order to display it on a map.
I created a basic controller that does all the api calls.
function mainController($scope, $http){
$http.get('/api/lastrun')
.success(function(data){
$scope.lastrun = data;
})
.error(function(data){
console.log('Error: ' + data);
});
}
lastrun has a path array that lets you access the each position.
I created a mapController using angular-leaf-directive
function mapController($scope, positionService){
angular.extend($scope, {
run: {
lat: 0.0,
lng: 0.0,
zoom: 4
},
path: {
p1: {
color: 'red',
weight: 2,
latlngs: [
{ lat: 51.50, lng: -0.082 }, //here is an example of lat and lng in this controller
{ lat: 48.83, lng: 2.37 },
{ lat: 0, lng: 7.723812 }
]
}
}
});
}
What I want to do seems pretty easy. I just want to put the array of positions I get while calling /api/lastrun into my mapController in latlngs.
I'm not completely familiar with Services in AngularJS, but I tried to built mine (positionService). However it didn't work.
Does anyone here know how I can proceed in order to create with my service an array containing a list of {lat : , lng: } and call it into my mapController ?
I would have done :
$scope.lastrun = [];
$http.get('/api/lastrun')
.success(function(data){
angular.forEach(data, function (value) {
$scope.lastrun.push({lat : value.lat, lng : value.lng});
});
}
})
and then :
path: {
p1: {
color: 'red',
weight: 2,
latlngs: $scope.lastrun
}
Hope this helps
I have finally found a solution. I use Adrien's solution in my service, not in my controller and then return the lastrunpos array to my mapController. Here's my code :
var selftracking = angular.module('selftracking',["leaflet-directive"])
selftracking.service('positionService', function($http){
var lastrunpos = [];
$http.get('/api/lastrun')
.success(function(data){
angular.forEach(data.path, function (value) {
lastrunpos.push({lat : value.latitude, lng : value.longitude});
});
});
return {
getPos : function() {
return lastrunpos;
}
}
});
function mainController($scope, $http){
//Get all the last activities in the front page
$http.get('/api/lastactivity')
.success(function(data){
$scope.lastactivity = data;
})
.error(function(data){
console.log('Error: '+ data);
});
$http.get('/api/lastrun')
.success(function(data){
$scope.lastrun = data;
})
.error(function(data){
console.log('Error: ' + data);
});
}
function mapController($scope, positionService){
angular.extend($scope, {
run: {
lat: 51.505,
lng: -0.09,
zoom: 4
},
path: {
p1: {
color: 'red',
weight: 8,
latlngs: positionService.getPos()
}
}
});
}

How to get google handle_geolocation_query map to display directions from users location

var endlocation = {
'center': '52.5606064,2.0312582999999904',
'zoom': 10
};
var start = navigator.geolocation.getCurrentPosition(handle_geolocation_query);
var themap;
var destination = "Wednesbury, WS10 7TB";
$(document).ready(function () {
$('#map').gmap({
'center': endlocation.center,
'zoom': endlocation.zoom,
'disableDefaultUI': true,
'callback': function () {
themap = this;
$('#submit').click(function () {
themap.displayDirections({
'origin': start,
'destination': destination,
'travelMode': google.maps.DirectionsTravelMode.DRIVING,
'unitSystem': google.maps.UnitSystem.IMPERIAL
}, {
'panel': document.getElementById('directions')
},
function (response, status) {
(status === 'OK') ? $('#results').show() : $('#results').hide();
});
return false;
});
}
});
navigator.geolocation.getCurrentPosition(handle_geolocation_query);
});
function handle_geolocation_query(position) {
start = new google.maps.LatLng(lat, lon);
themap.get('map').panTo(start);
}
I cant seem to figure out what I should pass to the handle_geolocation_query to get the map
to give directions from the users location to a fixed point. Thanks in advance for any help and sorry I'm a noob to maps. Heres the html:
<div id="map" style="height:500px;"><div>
If the rest of your code works, this should do the same as the submit, but automatically when the handle_geolocation_query function is run.
function handle_geolocation_query(position) {
start = new google.maps.LatLng(lat, lon);
themap.displayDirections({
'origin': start,
'destination': destination,
'travelMode': google.maps.DirectionsTravelMode.DRIVING,
'unitSystem': google.maps.UnitSystem.IMPERIAL
}, {
'panel': document.getElementById('directions')
},
function (response, status) {
(status === 'OK') ? $('#results').show() : $('#results').hide();
});
});

Categories

Resources