Skip to content

Instantly share code, notes, and snippets.

@RickCogley
Created March 1, 2017 04:35
Show Gist options
  • Save RickCogley/d24b3eb8814a31d8a72d38211534347c to your computer and use it in GitHub Desktop.
Save RickCogley/d24b3eb8814a31d8a72d38211534347c to your computer and use it in GitHub Desktop.
Geolocation in Teamdesk or dbFLEX

This is a clumsy attempt at making a list of clients nearby, based on the haversine formula.

The geolocation.js goes in setup resources. The script goes in a text section on a form.

This is likely broken, as it was built a long time ago, and not since vetted. There may be different API's available now, or, we may need to renew our subscription to the API that we originally signed up for.

<style type="text/css">
#map { margin-left:132px;color:red;width:560px;height:400px;display:inline-block;float:left; }
#clients { margin-left:15px;line-height:18px;float:left;height:400px;display:inline-block;overflow-y:scroll;max-width:300px; }
#dtbl td { border-bottom: 1px solid #000; }
td.cdistance { width: 100px; }
td.cname { width: 200px; }
</style>
<div id="data_wrapper">
<div id="map"></div>
<div id="clients"></div>
</div>
<script src="res.aspx/geolocation.js"></script>
<script src="//maps.google.com/maps/api/js?sensor=false"></script><script src="https://maps.gstatic.com/intl/en_ALL/mapfiles/api-3/17/6/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_us/mapfiles/api-3/17/4/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_us/mapfiles/api-3/17/4/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_us/mapfiles/api-3/17/4/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_us/mapfiles/api-3/17/4/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_ALL/mapfiles/api-3/17/3/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_ALL/mapfiles/api-3/17/3/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_ALL/mapfiles/api-3/17/3/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_ALL/mapfiles/api-3/17/3/main.js" type="text/javascript"></script><script src="https://maps.gstatic.com/intl/en_ALL/mapfiles/api-3/17/3/main.js" type="text/javascript"></script>
<script type="text/javascript" src="https://pro.dbflex.net/secure/db/15331/res.aspx/tdclient.js"></script>
<script type="text/javascript">
// Form Field Names
var fldLatitude = 'f_3484356';
var fldLongitude = 'f_3484355';
var fldLocation = 'f_3484358';
var fldIp = 'f_3484357';
var usermarker = 'https://pro.dbflex.net/secure/db/15331/res.aspx/customer.png';
var clientmarker = 'https://pro.dbflex.net/secure/db/15331/res.aspx/office.png';
var jsonData = 'https://pro.dbflex.net/secure/db/15331/res.aspx/json.php';
var jsonURL = (navigator.appName == 'Microsoft Internet Explorer') ? jsonData : 'http://freegeoip.net/json/';
// DATABASE ALIASES
var tbl = 'Client';
var tbl_fldClient = 'Client Code Upper Case';
var tbl_fldLatitude = 'Latitude';
var tbl_fldLongitude = 'Longitude';
var tbl_fldActive = 'Active?';
// HTML Elements
var divmap = document.getElementById("map");
var divclients = document.querySelector('#clients');
var elLatitude = document.querySelector('input[name="' + fldLatitude + '"]');
var elLongitude = document.querySelector('input[name="' + fldLongitude + '"]');
var elLocation = document.querySelector('input[name="' + fldLocation + '"]');
var elIp = document.querySelector('input[name="' + fldIp + '"]');
var elLatitudeView = document.querySelector('#' + fldLatitude + '_value.fs-view');
var elLongitudeView = document.querySelector('#' + fldLongitude + '_value.fs-view');
var API = TeamDesk.Client.API;
API.Server = gApiConfig.url;
API.SessionId=gApiConfig.sessionId;
var geocoder;
var map = new google.maps.Map(divmap, {
zoom: 12,
mapTypeControl: false,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker;
var storlat, storlng;
var infoArray = new Array();
function apiResultSucceeded (response) { return !TeamDesk.Client.Soap.IsFaultResult (response); }
function apiResultFailed (response) { return TeamDesk.Client.Soap.IsFaultResult (response) }
function apiResult (response) { if (apiResultSucceeded (response)) { getData(response); } }
function getData(data) {
var aRows = data.Rows;
var shtml = '<table cellpadding="5px" id="dtbl">';
shtml += '<tr><td class="cname"><strong>Clients</strong></td><td class="cdistance"><strong>Distance</strong></td></tr>';
loc1 = {
latitude: storlat,
longitude: storlng
};
aRows.forEach(function(info){
loc2 = {
latitude: info['Data'][tbl_fldLatitude],
longitude: info['Data'][tbl_fldLongitude]
};
addlatlng = new google.maps.LatLng(loc2.latitude, loc2.longitude);
marker = new google.maps.Marker({
position: addlatlng,
map: map,
icon: clientmarker
});
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(info['Data'][tbl_fldClient]);
infoWindow.open(map, this);
});
dist = calcDist(loc1, loc2);
infoArray.push({'client':info['Data'][tbl_fldClient],'distance':dist});
});
infoArray.sort(function(a,b){return a.distance - b.distance});
infoArray.forEach(function(info){
shtml += '<tr><td class="cname">' + info.client + '</td><td class="cdistance">' + info.distance + ' Km </td></tr>';
});
shtml += '</table>';
divclients.innerHTML += shtml;
}
// Define the entry point
function calculate_distances()
{
// Query the application for user menu details
API.Query ('SELECT [Active?],[Longitude],[Latitude],[Client Code Upper Case] FROM [' + tbl + '] where [' + tbl_fldActive + ']', apiResult);
}
function calcDist(loc1, loc2){
var rad = function(x) {return x*Math.PI/180;}
var R = 6371; // earth's mean radius in km
var dLat = rad(loc2.latitude - loc1.latitude);
var dLong = rad(loc2.longitude - loc1.longitude);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(loc1.latitude)) * Math.cos(rad(loc2.latitude)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
function showGoogleMap(mapCanvas, coords) {
geocoder = new google.maps.Geocoder();
latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
map.setCenter(latlng);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You are here!"
});
if(elLatitude && elLongitude) {
elLatitude.value = coords.latitude;
elLongitude.value = coords.longitude;
}
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: usermarker
});
if(elLocation){
elLocation.value = results[1].formatted_address;}
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
function getIP(){
var xhr = new XMLHttpRequest();
xhr.open('GET', jsonURL);
xhr.onload = function(e) {
var data = JSON.parse(this.response);
if(elIp){
elIp.value = data.ip;}
}
xhr.send();
}
function getCoordsAndShowMap() {
if(elLatitudeView && elLongitudeView) {
storlat = elLatitudeView.innerHTML;
storlng = elLongitudeView.innerHTML;
mycoords = {
latitude : storlat,
longitude : storlng
};
showGoogleMap(divmap, mycoords);
getIP();
}
else {
TD.getCurrentPosition(function(coords) {
storlat = coords.latitude;
storlng = coords.longitude;
// set position to TeamDesk controls
TD.setCurrentPosition(divmap, coords);
showGoogleMap(divmap, coords);
getIP();
}, divmap);
}
calculate_distances();
}
window.onload = getCoordsAndShowMap;
</script>
(function(undefined) {
if(window.TD === undefined) window.TD = {}
function message(msg, text) {
msg ? $(msg).text(text) : alert(text);
}
// calls success(coords) or displays error message to a control identified by msg jQuery selector
window.TD.getCurrentPosition = function(
/*function(coords)*/success,
/*optional jQuery*/msg)
{
// check if geolocation API is supported or enabled.
if(navigator.geolocation && navigator.geolocation.getCurrentPosition) {
// call geolocation service
navigator.geolocation.getCurrentPosition(
function(x) { success(x.coords); },
function(err) { message(msg, err.message); },
{ timeout: 60000 });
}
else {
message(msg, "The browser does not support geolocation API");
}
}
window.TD.setCurrentPosition = function(
/*jQuery*/id,
/*either Coordinates or msg jQuery selector*/coordsOrMsg)
{
function setPositionValues(coords) {
// works in "new layout" only, old layout needs patching
// determine the position of this block within a section
var thisSectionBlock = $(id).closest("dl");
var previousBlocks = thisSectionBlock.prevAll("dl");
// assume longitude immediately preceding and latitude stands before longitude.
// Then search for an <input> within a block to store the value
var longitude = $("input", previousBlocks[0]);
var latitude = $("input", previousBlocks[1]);
// set values, use $.format to produce locale-aware text
//latitude.val($.format(coords.latitude, "N6"));
//longitude.val($.format(coords.longitude, "N6"));
}
coordsOrMsg != null && coordsOrMsg.latitude != null && coordsOrMsg.longitude != null ?
// if we have something looking like coordinates, just set values
setPositionValues(coordsOrMsg) :
// otherwise assume it is message identifier and let browser handle the rest
this.getCurrentPosition(setPositionValues, coordsOrMsg);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment