Saturday, March 22, 2014

Suitlet code find the distance between two locations using third party API

Suitlet code to find the distance between two locations using third party (GOOGLE) API

Create a Suitlet Form 


Suitlet Code :
function suiteletDistance(request, response)
{
if(request.method == 'GET')
{
var form = nlapiCreateForm('Fare Calculator');
var field = form.addField('custpage_customer','select', 'Name','customer');
form.addField('custpage_from','text', 'From');
form.addField('custpage_to','text', 'To');          
form.addSubmitButton('Submit');             
response.writePage( form );  
}  
else 
if(request.method == 'POST')
{  
var name = request.getParameter("custpage_customer");  
var from = request.getParameter("custpage_from");  
var to = request.getParameter("custpage_to");  
var html='';  
html+='<html><head>';  
html+='<script src="https://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>';
Google API https://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A  
html+='<script type="text/javascript">function calcdistance(){';
html+='var location1="'+from+'";';  
html+='var location2="'+to+'";';  
html+='var geocoder = new GClientGeocoder();';  
html+='geocoder.getLocations(location1, function (response) {';  
html+='if (!response || response.Status.code != 200) {';  
html+='alert("Please Enter From Location");}else{';  
html+='location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};'; html+='geocoder.getLocations(location2, function (response) {';  
html+='if (!response || response.Status.code != 200){alert("Please Enter to Location");';  
html+='}else{location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};';  
html+='try{var glatlng1 = new GLatLng(location1.lat, location1.lon);var glatlng2 = new GLatLng(location2.lat, location2.lon);';  
html+='var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);var kmdistance = (miledistance * 1.609344).toFixed(1);';  
html+='alert(kmdistance);}catch (error){alert(error);}}});}});}';  
html+='</SCRIPT></head><body onload="calcdistance()">';    
html+='</BODY></HTML>';    
response.write(html);  
}
}

This Code will alert the distance (KM)

No comments: