I am creating a proof of concept using your "Building a geocoding app with Appery.io database and server code" example. My trouble is that I have the lat/long stored in the database and not an address because I want to reference building locations within a large complex and not physical address's.
Getting to my question: can you assist me with the js code to allow me to reference lat/long parameters and not a street address or city?
code
// Database Id
var dbId = "your database id" //Change this value to your database id
var responseBody = {};
// Get request parameters
var latitude = request.object().latitude;
var longitude = request.object().longitude;
var radius = request.object().radius;
// The function that calculates the distance between two points
function getDistance(lat1, lat2, lon1, lon2) {
var R = 3959; // Earth radius in miles
var dLat = (lat2 - lat1)*Math.PI/180;
var dLon = (lon2 - lon1)*Math.PI/180;
var lat1 = lat1*Math.PI/180;
var lat2 = lat2*Math.PI/180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
try {
// Check if all the necessary parameters are present and valid
if (latitude && longitude && radius && !isNaN(latitude) && !isNaN(longitude) && !isNaN(radius)) {
var results = [];
var params = {};
// Sort the results by contact name
params.sort = "contactName"
// Get all customers from the database
var customers = Collection.query(dbId, "customers", params);
for (var i = 0; i < customers.length; i++) {
// Geocode customer's address with Google API
var XHRResponse = XHR.send("GET", "https://maps.googleapis.com/maps/api/geocode/json", {
"parameters": {
"address": customers.address,
"sensor": "false"
}
});
console.log(XHRResponse);
if (XHRResponse.status == 200) {
// Get coordinates from the response
var lat = JSON.parse(XHRResponse.body).results[0].geometry.location.lat;
var lng = JSON.parse(XHRResponse.body).results[0].geometry.location.lng;
// If the customer's coordinates are within the radius,
// add the customer record to the results array
if (getDistance(lat, latitude, lng, longitude) <= radius) {
results.push(customers);
}
}
}
responseBody["results"] = results;
response.success(responseBody, "application/json");
} else {
response.error("Wrong parameters", 400);
}
} catch (e) {
console.log(e);
response.error("An error occured", 400);
}
/code