Saturday, July 24, 2010

Getting Longitude and Latitude using JavaScript for Microsoft Dynamics CRM 4.0

I've developed this script for my customer - it gets longitude and latitude using webservise http://rpc.geocoder.us/ based on address. The Code:

RefreshCoords = function()
{
var address = '';
if (crmForm.all.address1_line1.DataValue != null)
address = crmForm.all.address1_line1.DataValue;

if (crmForm.all.address1_line2.DataValue != null)
address += (address == '' ? '' : ', ') + crmForm.all.address1_line2.DataValue;

if (crmForm.all.address1_city.DataValue != null)
address += (address == '' ? '' : ', ') + crmForm.all.address1_city.DataValue;

if (crmForm.all.address1_stateorprovince.DataValue != null)
address += (address == '' ? '' : ', ') + crmForm.all.address1_stateorprovince.DataValue;

if (crmForm.all.address1_postalcode.DataValue != null)
address += (address == '' ? '' : ', ') + crmForm.all.address1_postalcode.DataValue;

var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("GET", "http://rpc.geocoder.us/service/rest?address=" + address, false);
xHReq.Send(null);

if (xHReq.statusText == "OK")
{
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
oXmlDoc.async = false;
oXmlDoc.loadXML(xHReq.responseText);

try
{
var long = parseFloat(oXmlDoc.selectSingleNode("//rdf:RDF/geo:Point/geo:long").text);
var lat = parseFloat(oXmlDoc.selectSingleNode("//rdf:RDF/geo:Point/geo:lat").text);

crmForm.all.address1_latitude.DataValue = lat;
crmForm.all.address1_longitude.DataValue = long;
}
catch(e){}
}
}


I've added this function to OnLoad event handler and pasted call of this functions to fields Address1 - Line 1, Address1 - Line 2, Address 1 - City, Address 1 - State/Province, Address1 - PostalCode.

But as I know this function will work only for users from USA and UK.

No comments:

Post a Comment