Wednesday, July 28, 2010

Getting Longitude and Latitude using JavaScript for Microsoft Dynamics CRM 4.0 Part 2

In my previous post I described how to make possible getting Longitude and Latitude. But chosen webservice was not able to resolve some of addresses. In this post I will describe how to get coordinates using Google API.


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;

try
{
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("GET", "http://maps.google.com/maps/api/geocode/xml?sensor=false&address=" + address, false);
xHReq.Send(null);

var resultXml =xHReq.responseXML;
var addressComponents = resultXml.selectNodes("//GeocodeResponse/result/geometry/location");
if (addressComponents != null && addressComponents.length > 0)
{
var long = parseFloat(resultXml.selectSingleNode("//GeocodeResponse/result/geometry/location/lng").nodeTypedValue);
var lat = parseFloat(resultXml.selectSingleNode("//GeocodeResponse/result/geometry/location/lat").nodeTypedValue);

crmForm.all.address1_latitude.DataValue = lat;
crmForm.all.address1_longitude.DataValue = long;
crmForm.all.address1_latitude.ForceSubmit = true;
crmForm.all.address1_longitude.ForceSubmit = true;
}

}
catch(e){}
}