Friday, July 30, 2010

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

Several days ago I redeveloped geocoding solution. After several days new issues were found. So I decided to search other webservice which will solve this Geocoding solution and stopped at Bing Maps.

First thing you have to do is to get key to work with Bing services. This can be done here - https://www.bingmapsportal.com/. Register your application and copy key.

I've build my solution based on this article. The code:

RefreshCoords = function()
{
var bingkey = "Paste your Key here";
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 url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + address + "&o=xml&key=" + bingkey;

try
{
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("GET", url, false);
xHReq.Send(null);

var resultXml =xHReq.responseXML;
var long = parseFloat(resultXml.selectSingleNode("//Response/ResourceSets/ResourceSet/Resources/Location/Point/Longitude").nodeTypedValue);
var lat = parseFloat(resultXml.selectSingleNode("//Response/ResourceSets/ResourceSet/Resources/Location/Point/Latitude").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){}
}