Page tree
Skip to end of metadata
Go to start of metadata

Introduction

DOTS Address Geocode – CA is a publicly available XML web service that provides latitude/longitude and metadata information about a physical Canadian address. The service provides geocoding information, such as the latitude and longitude location of a Canadian address, along with demographic information, such as the census tract, block and other metadata. 

DOTS Address Geocode – CA can provide instant address locations to websites or enhancement to contact lists

Integration

Integrating DOTS Address Geocode – CA into your application should be easy and straightforward. If you are using a common platform, Service Objects may already have sample code built that you can use:
https://www.serviceobjects.com/products/address-geocoding/address-validation-us

However, if you are using a common platform that does not already have sample code, you can ask Service Objects to build you an example. Email support@serviceobjects.com for more details. 

If your application does not require precise coordinate location, but will work with general-area mapping, GetBestMatch will give you a much higher match count than GetGeoLocation alone.

Web Service Structure:

Web services are methods that integrate with other applications via the web, and encapsulate complex business logic. Web services are too large a topic to cover in this document, but Service Objects has developed its web services to be as easy to integrate and as accessible as possible. 

DOTS Address Geocode – CA is a public XML web service that supports SOAP, POST and GET operations.

The host path, or physical location of the web service is here:
{+}https://trial.serviceobjects.com/gcc/

The location of the WSDL, or Web Service Definition Language document, is here (This is also accessible via the "Service Definition" link.):
 {+}https://trial.serviceobjects.com/gcc/soap.svc?WSDL

Important Note!
SOAP is done via POST, only with special XML markup in the post-body.

This XML is the definition of the web service, meaning its inputs, outputs, operations, and the like. Most likely, you will have another tool read this WSDL and make the operations available to you in your application. Whenever your utilities or IDE asks for a WSDL path to DOTS Address Geocode – CA, you can provide this one. 

Every web service has operations that it offers to subscribers – methods that do different work and return different output. Examining the links above, you will notice several of these operations available, which are described in detail later on. 


Code Snippets




Address GeoCode Canada C# Code Snippet
//Add a service to your application https://trial.serviceobjects.com/gcc/soap.svc?WSDL
GeoCoderCandada2Client GCCClient_Primary = new GeoCoderCandada2Client("DOTSGCC");
CanadianGeoCoderResponse response = GCCClient_Primary.GetGeoLocation(address, municipality, province, postalCode, LICENSE_KEY);
		
if (response.Error != null)
{
	//Process Error
}
else
{
	//Process Response		
}


Address GeoCode Canada Java Code Snippet
Location location= null;

Err error = null;
// Create soap request
DOTSGeoCoderCanadaLocator locator = new DOTSGeoCoderCanadaLocator();
// use ssl
locator.setDOTSGCCEndpointAddress("https://trial.serviceobjects.com/gcc/soap.svc?WSDL");
IGeoCoderCanada gcc= locator.getDOTSGCC();
DOTSGCCStub soap = (DOTSGCCStub)gcc;
soap.setTimeout(5000);
location= soap.getGeoLocation(address, municipality, province, postalCode, LICENSE_KEY);

error = location.getError();
if(resp == null || (error != null && error.getTypeCode() == "3"))
{
	throw new Exception();
}
 
//Process Results
if(error == null){
	//DOTS Address GeoCode Canada 2 Results	
}
//Process Errors
else{
	//DOTS Address GeoCode Canada 2 Error Results	
}


Address GeoCode Canada PHP Code Snippets
<?php
// Set these values per web service <as needed>
$wsdlUrl = "https://trial.serviceobjects.com/gcc/soap.svc?WSDL";

$params['Address'] 		= $Address;
$params['Municipality'] = $Municipality;
$params['Province'] 	= $Province;
$params['PostalCode'] 	= $PostalCode;
$params['LicenseKey'] 	= $LicenseKey;

$soapClient = new SoapClient($wsdlUrl, array( "trace" => 1 ));
$result = $soapClient->GetGeoLocation($params);
if (!isset($result->GetGeoLocationResult->Error)) {
	foreach($result->GetGeoLocationResult->GeoLocationInfo as $k=>$v) {
		echo $k . ", " . $v;
	}
} else {
	foreach($result->GetGeoLocationResult->Error as $k=>$v) {
		echo $k . ", " . $v;
	}
}
?>


Address GeoCode Canada RoR Code Snippets
class RequestsController < ApplicationController

	def show 
		@request = Request.find(params[:id])

		#Formats inputs into a hash to pass to Soap Client
		#Hash Keys must be named as they are shown here.
		message = 	{
					"Address" => @request.address,
					"Municipality" => @request.municipality,
					"Province" => @request.province,
					"PostalCode" => @request.postalcode,
					"LicenseKey" => @request.licensekey,
					}
		
		#Implemented to make the code more readable when accessing the hash			
		@agcaresponse = :get_geo_location_response
		@agcaresult = :get_geo_location_result
		@agcaerror = :error

		#Set Primary and Backup URLs here as needed
		dotsAGCAPrimary = "https://trial.serviceobjects.com/gcc/soap.svc?WSDL"
		dotsAGCABackup = "https://trial.serviceobjects.com/gcc/soap.svc?WSDL"

		begin
			#initializes the soap client. The convert request keys global is necessary to receive a response from the service.
			client = Savon.client(	wsdl: dotsAGCAPrimary,
									element_form_default: :qualified,
									convert_request_keys_to: :camelcase
								 )
			#Calls the operation with given inptus and converts response to a hash.
			response = client.call(:get_geo_location, message: message).to_hash
			#Checks to see what results came back from the service
			processresults(response)			
			
			#If an error occurs during the call, this will use the backup url and attempt to retrieve data.
			rescue Savon::Error => e
			begin
			backupclient = Savon.client(	wsdl: dotsAGCABackup,
											element_form_default: :qualified,
											convert_request_keys_to: :camelcase
									   )
			#Sets the response to the backclient call to the operation and converts response to a hash.
			response = backupclient.call(:get_geo_location, message: message).to_hash
			processresults(response)

			end
		end
	end
	private 
	def processresults(response)
	
			#Processes Error Response from soap Client		
			
			#Processes Valid response from soap client	
	end
end


Address Geocode Canada Python Code Snippet
    mAddress =  Address.get()
    if mAddress is None or  mAddress == "":
         mAddress = " "
    mMunicipality = Municipality.get()
    if mMunicipality is None or mMunicipality == "":
        mMunicipality = " "
    mProvince = Province.get()
    if mProvince is None or mProvince == "":
        mProvince = " "
    mPostalCode = PostalCode.get()
    if mPostalCode is None or mPostalCode == "":
        mPostalCode = " "
    mLicenseKey = LicenseKey.get()
    if mLicenseKey is None or mLicenseKey == "":
        mLicenseKey = " "

    #Set the primary and backup URLs as needed
    primaryURL = 'https://trial.serviceobjects.com/gcc/soap.svc?WSDL'
    backupURL = 'https://trial.serviceobjects.com/gcc/soap.svc?WSDL'

    #This block of code calls the web service and prints the resulting values to the screen
    try:
        client = Client(primaryURL)
        result = client.service.GetGeoLocation(Address=mAddress, Municipality=mMunicipality, Province=mProvince, PostalCode=mPostalCode, LicenseKey=mLicenseKey)
        #Loops through either the error result or proper result and displays values to the screen.
        if hasattr(result, 'Error') :
            for value in result.Error:
                Label(swin.window, text=str(value[0]) + " : " + str(value[1]) if value[1] else str(value[1])+": None").pack()
       #Handel response and check for errors
 
	 #Tries the backup URL if the primary URL failed
    except:
        try:
            client = Client(backupURL)
            result = client.service.GetGeoLocation(Address=mAddress, Municipality=mMunicipality, Province=mProvince, PostalCode=mPostalCode, LicenseKey=mLicenseKey)
           #Handel response and check for errors

        #If the backup call failed then this will display an error to the screen
        except:
            Label(swin.window, text='Error').pack()
            print (result)
   


Address GeoCode Canada ColdFusion Code Snippet
<!--Makes Request to web service --->
<cfscript>
		try
		{
			if (isDefined("form.Action") AND Action neq "")
			{
				wsresponse = CreateObject("webservice", "https://trial.serviceobjects.com/gcc/soap.svc?WSDL");							  
				outputs = wsresponse.getGeoLocation("#Address#", "#Municipality#", "#Province#", "#PostalCode#" ,"#LicenseKey#");
			}
		}
	catch(any Exception){
		try
			{
				if (isDefined("form.Action") AND Action neq "")
				{
					wsresponse = CreateObject("webservice", "https://trial.serviceobjects.com/gcc/soap.svc?WSDL");							  
					outputs = wsresponse.getGeoLocation("#Address#", "#Municipality#", "#Province#", "#PostalCode#" ,"#LicenseKey#");
				}
			}
			catch(any Exception)	{
		  		 writeoutput("An Error Has Occured. Please Reload and try again");		  		 
		 		}
	    }
</cfscript>
 
<cftry>


Address GeoCode Canada VB Code Snippet
Try
    Dim ws As New AGCA.DOTSGeoCoderCanadaSoapClient
    Dim response As AGCA.Location
    response = ws.GetGeoLocation(Address.Text, Municipality.Text, Province.Text, PostalCode.Text, LicenseKey.Text)
    If (response.Error Is Nothing) Then
        ProcessValidResponse(response)
    Else
        ProcessErrorResponse(response.Error)
    End If
Catch
    ''Set the Primary and Backup Service References as necessary
    Try
        Dim wsbackup As New AGCA.DOTSGeoCoderCanadaSoapClient
        Dim response As AGCA.Location
        response = wsbackup.GetGeoLocation(Address.Text, Municipality.Text, Province.Text, PostalCode.Text, LicenseKey.Text)
        If (response.Error Is Nothing) Then
            ProcessValidResponse(response)
        Else
            ProcessErrorResponse(response.Error)
        End If
    Catch ex As Exception
        resultsLabel.Visible = True
        resultsLabel.Text = ex.Message
    End Try
End Try


Address GeoCode Canada Apex Code Snippet
wwwServiceobjectsCom.Location result;
try{
wwwServiceobjectsCom.DOTSGeoCoderCanadaSoap client = new wwwServiceobjectsCom.DOTSGeoCoderCanadaSoap();
result = client.GetGeoLocation([Address], [Municipality], [Province], [PostalCode], [LicenseKey]);
}
catch(Exception ex){
 //If the first request failed try the failover endpoint
wwwServiceobjectsCom.DOTSGeoCoderCanadaSoap backupClient = new wwwServiceobjectsCom.DOTSGeoCoderCanadaSoap();
//The backup environment will be provided to you upon purchasing a production license key
backupClient.endpoint_x = 'https://trial.serviceobjects.com/gcc/soap.svc/soap';
result = backupClient.GetGeoLocation([Address], [Municipality], [Province], [PostalCode], [LicenseKey]);
}


Address GeoCode Canada TSQL Code Snippet
SET @requestBody ='<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'+
				   '<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
				   '<GetGeoLocation xmlns="http://www.serviceobjects.com/">'+
				   '<Address>' + @address + '</Address>'+
				   '<Municipality>' + @municipality + '</Municipality>'+
				   '<Province>' + @province + '</Province>'+
				   '<PostalCode>' + @postalcode + '</PostalCode>'+
				   '<LicenseKey>' + @key + '</LicenseKey>'+
				   '</GetGeoLocation>'+
				   '</s:Body>'+
				   '</s:Envelope>'

SET @requestLength = LEN(@requestBody)

	--If a production key is purchased, this will execute the failover 
IF @isLiveKey = 1
BEGIN
	EXEC sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
	EXEC sp_OAMethod @obj, 'Open', NULL, 'POST', 'https://trial.serviceobjects.com/gcc/', false
	EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'HOST', 'ws.serviceobjects.com'
	EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'Content-Type', 'text/xml; charset=UTF-8'
	EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'SOAPAction', '"http://www.serviceobjects.com/GetGeoLocation"'
	EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'Content-Length', @requestLength 
	EXEC sp_OAMethod @obj, 'send', NULL, @requestBody
	EXEC sp_OAGetProperty @obj, 'Status', @responseCode OUTPUT
	EXEC sp_OAGetProperty @obj, 'StatusText', @statusText OUTPUT
	EXEC sp_OAGetProperty @obj, 'responseText', @response OUTPUT
			
	--Checks the Response for a fatal error or if null. 
	IF @response IS NULL
	BEGIN
		EXEC sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
		EXEC sp_OAMethod @obj, 'Open', NULL, 'POST', 'https://trial.serviceobjects.com/gcc/', false
		EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'HOST', 'wsbackup.serviceobjects.com'
		EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'Content-Type', 'text/xml; charset=UTF-8'
		EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'SOAPAction', '"http://www.serviceobjects.com/GetGeoLocation"'
		EXEC sp_OAMethod @obj, 'setRequestHeader', NULL, 'Content-Length', @requestLength 
		EXEC sp_OAMethod @obj, 'send', NULL, @requestBody
		EXEC sp_OAGetProperty @obj, 'Status', @responseCode OUTPUT
		EXEC sp_OAGetProperty @obj, 'StatusText', @statusText OUTPUT
		EXEC sp_OAGetProperty @obj, 'responseText', @response OUTPUT
	END
END


Address GeoCode Canada NodeJS Code Snippet
var args = {Address: 'Address', 
			Municipality: 'Municipality', 
			Province: 'Province', 
			PostalCode: 'PostalCode', 
			LicenseKey: 'LicenseKey'};
soap.createClient(primaryUrl, function(err, client) {
	
  	client.GetGeoLocation(args, function(err, result) {
  		//This is where you will handle the service results. Your business logic will determine
  		//how the validated information is used.
  		//The exact output can be found in our documentation:
  		//https://docs.serviceobjects.com/display/devguide/DOTS+Address+Geocode++-++Canada
  		if(err != null || result == null)
  		{
  			//There was an error that occurred that wasn't part of the normal service response
  			return;
  		}
  		else{
  			//Check for an error object
  			if(result.GetGeoLocationResult.Error != null)
  			{
  				//An error object was returned by the service and you will want to use 
  				//the following failover logic.
  				//If it was a Service Objects Fatal exception we recommend trying 
  				//a backup server. 
  				if(result.GetGeoLocationResult.Error.Number == "4")
  				{
  					//The actual backup url will be provided when you purchase a license key
  					var backupUrl = 'https://trial.serviceobjects.com/gcc/soap.svc?WSDL';
  					soap.createClient(backupUrl, function(failoverErr, backupClient) {
	
  						backupClient.GetGeoLocation(args, function(failoverErr, failoverResult) {
  							//Handle the failoverErr or failoverResult objects.
  							return;
  						});
  					});
  				}
  				else{
  					//The Error object isn't of the type "Service Objects Fatal" so
  					//there is no need to use the failover logic. There was some Error of
  					//type Authorization, User Input, or Domain Specific.
  					response.writeHead(200, "OK", {'Content-Type': 'text/html'});
 	     			response.end(JSON.stringify(result));
  					return;
  				}
  			}
  			else{
  				//You have a non Error response.
  				//All of the data will reside within the result object
  				//As an easy to see what the service returns I am returning a JSON 
 	     		//serialized version as the response.
      			response.writeHead(200, "OK", {'Content-Type': 'text/html'});
 	     		response.end(JSON.stringify(result));
      			return;
  			}
  		}
 		});
});



Address GeoCoder Canada C# Rest Snippet
         try
            {
                result = HttpGet(mainURL);
                //NULL ERROR || FATAL ERROR RETURNED -- TRY BACKUP 
                if (result == null || (result.Error != null && result.Error.Number == "3"))
                {
                    return HttpGet(backupURL);
                }
                else
                {
                    return result;
                }
            }
            catch (Exception)
            {   //ERROR IN MAIN URL - USING BACKUP
                return HttpGet(backupURL);
            }
 
	public static GCCResponse HttpGet(string requestUrl)
        {
            try
            {
                System.Diagnostics.Debug.Write(requestUrl);
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                request.Timeout = WEB_SERVICE_REQUEST_TIMEOUT;//timeout for get operation
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        response.StatusCode,
                        response.StatusDescription));
                    //prrocessing response
                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(GCCResponse));
                    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                    GCCResponse jsonResponse = objResponse as GCCResponse;
                    return jsonResponse;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }


Address GeoCoder Canada Java Rest Snippet
		JSONObject results = RestClient(mainURL);	
		if (ErrorMessages != null || (results.has("Error") && results.getJSONObject("Error").get("Number") == "3")) {
			// BACKUP
			results = RestClient(backupURL);
		}
		
		
		return results;


Address GeoCoder Canada PHP Rest Snippet
$URL = "https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=".urlencode($Address)."&Municipality=".urlencode($Municipality)."&Province=".urldecode($Province)."&PostalCode=".urldecode($PostalCode)."&LicenseKey=".urlencode($LicenseKey);

//use backup url once given purchased license key
$backupURL = "https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=".urlencode($Address)."&Municipality=".urlencode($Municipality)."&Province=".urldecode($Province)."&PostalCode=".urldecode($PostalCode)."&LicenseKey=".urlencode($LicenseKey);

	// Get cURL resource
	$curl = curl_init();
	curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $URL, CURLOPT_USERAGENT => 'Service Objects Geocoder Canada'));
	curl_setopt($curl, CURLOPT_TIMEOUT, 50); //timeout in seconds
	// Send the request & save response to $resp
	$resp = curl_exec($curl);
	
	// Close request to clear up some resources
	if($resp == false)
	{
		echo "IN back up block";
		curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $backupURL, CURLOPT_USERAGENT => 'Service Objects Geocoder Canada'));
		curl_setopt($curl, CURLOPT_TIMEOUT, 50); //timeout in seconds
		// Send the request & save response to $resp
		$resp = curl_exec($curl);
		if($resp == false)
		{
			echo "<b> Both rest calls failed </b>";
			curl_close($curl);
			return;
		}
	
	
	}


Address GeoCoder Canada RoR Rest Snippet
      @request = Request.find(params[:id])

      #This sets the default timeout for HTTParty get operation. This must be set in order to use the gem
      default_timeout = 10

      address = @request.address
      municipality = @request.municipality
      province = @request.province
      postalcode = @request.postalcode
      licensekey = @request.licensekey
      
      #Set Primary and Backup URLs as needed. Normalizes the URL to that it can be passed to the web service.
      primaryURL = URI.encode("https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=" + address + "&Municipality=" + municipality + "&Province=" + province + "&PostalCode=" + postalcode + "&LicenseKey=" + licensekey)
      backupURL = URI.encode("https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation=" + address + "&Municipality=" + municipality + "&Province=" + province + "&PostalCode=" + postalcode + "&LicenseKey=" + licensekey)
      
      #These are set to access the hash that is returned
      @agcaresult ="Location"
      @agcaerror = "Error"
      
        #Begins the call the RESTful web service
      begin
      	
        response = HTTParty.get(primaryURL, timeout: default_timeout)
        #processes the response to display to the screen
        
        #Passes the response returned from HTTParty and processes them depending on the results
        processresults(response)

        
       rescue StandardError => e
       		begin
       		#uses the backupURl in the event that the service encountered an error
       		response = HTTParty.get(URI.encode(backupURL), timeout: default_timeout)
          
          #processes the response returned from using the backupURL
       		processresults(response)
          #If the backup url railed this will raise an error and display the 
          #error message returned from the HTTParty gem.
       		rescue StandardError => error
       			@status = error.message
       			@displaydata = {"Error" => "A Big Error Occured"}
       		end

      end


Address GeoCoder Canada Python Rest Snippet
    #Set the primary and backup URLs as necessary
    primaryURL = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?'
    backupURL = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?'

    #The Requests package allows the user to format the path parameters like so instead of having to manually insert them into the URL
    inputs = {'Address': mAddress, 'Municipality': mMunicipality, 'Province': mProvince, "PostalCode": mPostalCode, 'LicenseKey': mLicenseKey}
    try:
        result = requests.get(primaryURL, params=inputs)
        #Parses the XML response from the service into a python dictionary type
        outputs = xmltodict.parse(result.content)
        #checks the output for Errors and displays the info accordingly
        if 'Error' in outputs['Location']:
            #loops through the response from the service and prints the values to the screen.
            for key, value in outputs['Location']['Error'].iteritems():
                Label(swin.window, text=str(key) + " : " + str(value)).pack()
        else:
            #Removes unnecessary values that were parsed from the original xml response
            outputs['Location'].pop("@xmlns:xsi", None)
            outputs['Location'].pop("@xmlns:xsd", None)
            outputs['Location'].pop("@xmlns", None)
            for key, value in outputs['Location'].iteritems():
                Label(swin.window, text=str(key) + " : " + str(value)).pack()

    #Uses the backup URL in the event that the primary URL failed
    except:
        try:
            result = requests.get(backupURL, params=inputs)
            #Parses the XML response from the service into a python dictionary type
            outputs = xmltodict.parse(result.content)
            #checks the output for Errors and displays the info accordingly
            if 'Error' in outputs['Location']:
                #loops through the response from the service and prints the values to the screen.
                for key, value in outputs['Location']['Error'].iteritems():
                    Label(swin.window, text=str(key) + " : " + str(value)).pack()
            else:
                #Removes unnecessary values that were parsed from the original xml response
                outputs['Location'].pop("@xmlns:xsi", None)
                outputs['Location'].pop("@xmlns:xsd", None)
                outputs['Location'].pop("@xmlns", None)
                for key, value in outputs['Location'].iteritems():
                    Label(swin.window, text=str(key) + " : " + str(value)).pack()


Address GeoCoder Canada ColdFusion Snippet
<!--Makes Request to web service --->
<cfIf isDefined("form.Action") AND Action neq "" >
	<cftry>
		<cfset primaryURL = "https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=#Address#&Municipality=#Municipality#&Province=#Province#&PostalCode=#PostalCode#&LicenseKey=#LicenseKey#">
		<cfhttp url="#primaryURL#" method="get" result="response">
		<cfset outputs = XmlParse(response.FileContent)>
		<cfcatch>
			<cftry>
				<cfset backupURL = "https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=#Address#&City=#City#&State=#State#&PostalCode=#PostalCode#&LicenseKey=#LicenseKey#">
				<cfhttp url="#backupURL#" method="get" result="response">
				<cfset outputs = XmlParse(response.FileContent)>				
				<cfcatch >
					<cfoutput >
						The Following Error Occured: #response.StatusCode#
					</cfoutput>
				</cfcatch>
			</cftry>
		</cfcatch>
	</cftry>
</cfif>


Address GeoCode Canada VB Rest Code Snippet
'encodes the URLs for the get Call. Set the primary and back urls as necessary
Dim primaryurl As String = "https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=" + address + "&Municipality=" + municipality + "&Province=" + province + "&PostalCode=" + postalcode + "&LicenseKey=" + licensekey
Dim backupurl As String = "https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=" + address + "&Municipality=" + municipality + "&Province=" + province + "&PostalCode=" + postalcode + "&LicenseKey=" + licensekey
Dim wsresponse As AGCAResponse.Location = httpGet(primaryurl)

'checks if a response was returned from the service, uses the backup url if response is null or a fatal error occured.
If wsresponse Is Nothing OrElse (wsresponse.[Error] IsNot Nothing AndAlso wsresponse.[Error].Number = "3") Then
    wsresponse = httpGet(backupurl)
End If
If wsresponse.[Error] IsNot Nothing Then
    ProcessErrorResponse(wsresponse.[Error])
Else
    ProcessSuccessfulResponse(wsresponse)

End If


Address GeoCode Canada TSQL Code Snippet
IF @isLiveKey = 1
BEGIN
	SET @sUrl = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=' + @address + '&Municipality=' + @municipality + '&Province=' + @province + '&PostalCode=' + @postalcode + '&LicenseKey=' + @key
	EXEC sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
	EXEC sp_OAMethod @obj, 'Open', NULL, 'Get', @sUrl, false
	EXEC sp_OAMethod @obj, 'send'
	EXEC sp_OAGetProperty @obj, 'responseText', @response OUT
			
	--Checks the Response for a fatal error or if null. 
	IF @response IS NULL
	BEGIN
		SET @sBackupUrl = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=' + @address + '&Municipality=' + @municipality + '&Province=' + @province + '&PostalCode=' + @postalcode + '&LicenseKey=' + @key
		EXEC sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
		EXEC sp_OAMethod @obj, 'Open', NULL, 'Get', @sBackupUrl, false
		EXEC sp_OAMethod @obj, 'send'
		EXEC sp_OAGetProperty @obj, 'responseText', @response OUT
	END
END


Address GeoCode Canada NodeJS Code Snippet
var Address = 'Address';
var Municipality ='Municipality';
var Province ='Province'; 
var PostalCode ='PostalCode';
var LicenseKey ='LicenseKey';
//Set backup and primary URL as necessary
var primaryUrl = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=' + Address + '&Municipality=' + Municipality +'&Province=' + Province +'&PostalCode=' + PostalCode +'&LicenseKey=' + LicenseKey;
var backupUrl = 'https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=' + Address + '&Municipality=' + Municipality +'&Province=' + Province +'&PostalCode=' + PostalCode +'&LicenseKey=' + LicenseKey;

var req = http.get(primaryUrl, function(res) {
	res.setEncoding('utf8');
	res.on('data', function (results) {
		var parser = require('xml2js').Parser({explicitArray: false,ignoreAttrs: true});
		parser.parseString(results, function (err, outputs) {
			if (outputs.Location.Error !=  null)
			{
				//Indicates a Fatal error has occured. If this happens, the logic will then failover to the backup url
				if (outputs.Location.Error.Number == "4")
				{
					var backupReq = http.get(backupUrl, function(backupRes) {
						backupRes.setEncoding('utf8');
						backupRes.on('data', function (results) {
							var parser = require('xml2js').Parser({explicitArray: false,ignoreAttrs: true});
							parser.parseString(results, function (err, outputs) {
								console.log("Backup Call Was Used.");
								response.end(JSON.stringify(outputs , null, 3));
								});
							});
						});
				}
				else
				{
					//Will Display the JSON Formatted Error Response here
					response.end(JSON.stringify(outputs, null, 3));
					return;
				}
			}
			else
			{
				//Will Display the JSON Formatted Valid Response here
				response.end(JSON.stringify(outputs, null, 3));
				return;
			}
		});
	});
});

You can find and download full sample code to our services in various languages (PHP, JAVA and C#) by clicking here. Below is a C# version.

If you are looking for a particular integration not listed in our documentation please contact us at support@serviceobjects.com.

C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ServiceObjects
{
    public partial class _Default : System.Web.UI.Page
    {
        // Declare proxy object to handle requests to Service Objects DOTSGeoCoderCanada Service
        private com.serviceobjects.trial.DOTSGeoCoderCanada gc;
        // Declare result object to handle response from DOTSGeoCoderCanada Service
        private com.serviceobjects.trial.Location location;
        // Declare result object to any errors recieved during request
        private com.serviceobjects.trial.Err Error;
        // Declare failover string to handle any failed request to primary endpoint. This would usually be implemented
        // in 
        private const string FailOver = "https://trial.serviceobjects.com/gcc/";
        protected void Page_Load(object sender, EventArgs e)
        {
            gc = new com.serviceobjects.trial.DOTSGeoCoderCanada();
            location = null;
            ResultLabel.Visible = false;
            ResultLabel.Text = "";
        }
        protected void btn_GO_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                try
                {
                    location = gc.GetGeoLocation(Address.Text, Municipality.Text, Province.Text, PostalCode.Text, LicenseKey.Text);
                }
                catch (Exception ex)
                {
                    gc.Url = FailOver;
                    location = gc.GetGeoLocation(Address.Text, Municipality.Text, Province.Text, PostalCode.Text, LicenseKey.Text);
                }
                if (location != null)
                {
                    if (location.Error == null)
                    {
                        
                        ResultLabel.Text = "<b>Address Geocode Canada Results:</b><table border='1'><tr><td>Latitude</td><td>" + location.Latitude + "</td></tr>";
                        ResultLabel.Text += "<tr><td>Longitude</td><td>" + location.Longitude + "</td></tr>";
                        ResultLabel.Text += "<tr><td>Postal Code</td><td>" + location.PostalCode + "</td></tr>";
                        ResultLabel.Text += "</table>";
                        ResultLabel.Visible = true;
                    }
                    else
                    {
                        Error = location.Error;
                        ResultLabel.Text = "<b>Errors Found!</b><table border='1'><tr><td>Error Description</td><td>" + Error.Desc + "</td></tr>";
                        ResultLabel.Text += "<tr><td>Error Code</td><td>" + Error.Number + "</td></tr>";
                        ResultLabel.Text += "</table>";
                        ResultLabel.Visible = true;
                    }
                }
                else
                {
                    ResultLabel.Text = "Unable to make request";
                    ResultLabel.Visible = true;
                }
            }
            catch (Exception ex)
            {
                ResultLabel.Text = "Unable to create object";
                ResultLabel.Visible = true;
            }
        }

    }
}


GetPostalCodeInfo Example Request and Response


URL Request: 
https://trial.serviceobjects.com/GCC/api.svc/xml/GetPostalCodeInfo?PostalCode=k1k3b8&LicenseKey=licenseKey


XML Response
<PostalCodeResponse xmlns="http://serviceobjects.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<PostalCodeInfo>
<Latitude>45.423767</Latitude>
<Longitude>-75.637449</Longitude>
<PostalCode>k1k 3b8</PostalCode>
<TimeZone>EASTERN</TimeZone>
<DST>Y</DST>
<AreaCode>613</AreaCode>
<City>OTTAWA</City>
<CityPopulation>29724</CityPopulation>
<Province>Ontario</Province>
<ProvinceAbbreviation>ON</ProvinceAbbreviation>

</PostalCodeInfo>
</PostalCodeResponse>


URL Request: 
https://trial.serviceobjects.com/GCC/api.svc/json/GetPostalCodeInfo?PostalCode=k1k3b8&LicenseKey=licenseKey


JSON Response
{"Latitude":"45.423767","Longitude":"-75.637449","PostalCode":"k1k 3b8","TimeZone":"EASTERN","DST":"Y","AreaCode":"613","City":"OTTAWA","CityPopulation":"29724","Province":"Ontario","ProvinceAbbreviation":"ON"}

GetGeoLocationByMunicipalityProvince Example Request and Response


URL Request:
https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocationByMunicipalityProvince?Municipality=North+York&Province=ON&LicenseKey=licenseKey


XML Response
<GeoLocationResponse xmlns="http://serviceobjects.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<GeoLocationInfo>
<Latitude>43.624793404</Latitude>
<Longitude>-79.19743202</Longitude>
</GeoLocationInfo>
</GeoLocationResponse>


URL Request:
https://trial.serviceobjects.com/GCC/api.svc/json/GetGeoLocationByMunicipalityProvince?Municipality=North+York&Province=ON&LicenseKey=licenseKey


JSON Response
{"Latitude":"43.624793404","Longitude":"-79.19743202"}

GetGeoLocation Example Request and Response


URL Request: 
https://trial.serviceobjects.com/GCC/api.svc/xml/GetGeoLocation?Address=8+Garmond+Court&Municipality=North+York&Province=ON&PostalCode=M3C1Z4&LicenseKey=licenseKey


XML Response
<GeoLocationResponse xmlns="http://serviceobjects.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<GeoLocationInfo>
<Latitude>43.726747</Latitude>
<Longitude>-79.333910</Longitude>
<PostalCode>M3C1Z4</PostalCode>
</GeoLocationInfo>
</GeoLocationResponse>


URL Request: 
https://trial.serviceobjects.com/GCC/api.svc/json/GetGeoLocation?Address=8+Garmond+Court&Municipality=North+York&Province=ON&PostalCode=M3C1Z4&LicenseKey=licenseKey


JSON Response
{"Latitude":"43.727268","Longitude":"-79.334984","PostalCode":"M3C 1Z4","MatchCode":"Property"}


List of Operations

GetGeoLocation (Recommended Operation) --
GetPostalCodeInfo -- Returns latitude, longitude, postal code, time zone, DST, area code, city, city population, province, province abbreviation, dma
GetGeoLocationByMunicipality -- Returns latitude/longitude information for a given municipality


Operation Definitions

This document defines the input, output and behavior of the web service operations in DOTS Address Geocode – CA. Each operation has its own unique behavior and output, though some of the operations are very similar.

Important Note!
Every geocoding system is different, and some even use different standards for gathering and calculating coordinates. Because of this, using coordinates from one system may not look to be at the exact location on a different system.

For example, Google Maps is a great tool for plotting geocoding coordinates on a viewable map. However, the data used for generating these maps is different than the data that Service Objects uses for generating geocoding coordinates. Thus, some points plotted on Google Maps may not look to be in the precise location; they may look exactly right or look to be several hundred feet away.

You should examine your own business needs first before exploring what DOTS Address Geocode – CA can provide. Different operations may be necessary based on the information you have, and the granularity of data you need.

GetGeoLocation (Recommended Operation)

This is the basic operation for finding the latitude/longitude coordinates of an address. This operation takes a standard Canadian address (Address, Municipality, Province, Postal Code) and will try to find the exact street location's coordinates. It cannot always find the location, especially when it comes to empty lots or new construction areas. 

First, DOTS Address Geocode – CA will attempt to correct and normalize the address to make it more likely to geocode properly. You don't need to worry about fixing the address before sending it to DOTS Address Geocode – CA, unless you want to filter out invalid or non-existent addresses beforehand. 

This operation requires the Address value, and either Municipality and Province, or the Zip code. Providing all inputs is recommended.

GetGeoLocation Inputs

Name

Type

Description

Address

String

Address line of the address to geocode. For example, "123 Main Street".

Municipality

String

The municipality of the address to geocode. For example, "Cayuga". The municipality isn't required, but if one is not provided, the postal code is required.

Province

String

The province of the address to geocode. For example, "ON". This does not need to be contracted, full province names will work as well.The province isn't required, but if one is not provided, the postal code is required.

Postal Code

String

The postal code of the address to geocode. A postal code isn't required, but if one is not provided, the municipality and province are required.

License Key

String

Your license key to use the service. Sign up for a free trial key at https://www.serviceobjects.com/products/address-geocoding/address-geocode-canada

GetGeoLocation Outputs

Name

Type

Values

Description

Latitude

String

Number

The latitude of the given
address.

Longitude

String

Number

The longitude of the given
address.

Postal Code

String

Number

Postal code of given address.

Match Code

String

Property, PostalCode or Municipality

A string indicating what to what level the input coordinates could be geocoded .

GetPostalCodeInfo

This operation is almost exactly like GetGeoLocation, but rather than geocoding given a specific address, DOTS Address Geocode – CA will geocode given a postal code. The coordinates given are an average centroid of a given postal code and often times match precisely to the street location.

GetPostalCodeInfo Inputs

Name

Type

Description

Postal Code

String

The postal code to geocode.

License Key

String

Your license key to use the service. Sign up for a free trial key at
https://www.serviceobjects.com/products/address-geocoding/address-geocode-canada

GetPostalCodeInfo Outputs

Name

Type

Values

Description

Latitude

String

Number

The latitude of the given postal code plus four.

Longitude

String

Number

The longitude of the given postal code plus four.

Postal Code

String

String

The postal code of the given input.

Time Zone

String

String

The time zone of the given postal code.

DST

String

Char

Boolean value determines if location uses daylight savings time.

Area Code

String

Number

The area code for the given postal code.

City

String

String

The city for the given postal code.

City Population

String

Number

The city population for the given postal code.

Province

String

String

The province for the given postal code.

GetGeoLocationByMunicipalityProvince

This operation is almost exactly like GetGeoLocation except that it provides latitude/longitude coordinates based on provided municipality and province.

GetGeoLocationByMuncipalityProvince Inputs

Name

Type

Description

Municipality

String

The municipality to geocode.

Province

String

The province to geocode.

License Key

String

Your license key to use the service. Sign up for a free trial key at
https://www.serviceobjects.com/products/address-geocoding/address-geocode-canada

GetGeoLocationByMunicipalityProvince Outputs

Name

Type

Values

Description

Latitude

String

Number

The latitude of the given municipality and province.

Longitude

String

Number

The longitude of the given municipality and province.

Postal Code

String

String

The postal code of the given municipality and province


Error Codes

Error codes in DOTS Address Geocode – CA are the same for all operations. They are as follows: 

Error Code 1 – "Input cannot be less than zero length
This error means the web service did not get any input. The connection to the service was made, and data was transferred, but no parameters were passed that the service could understand.
This error often happens when input is passed to the service with namespaces that the service does not understand. Applying a namespace to any of the parameters (Address or LicenseKey, in this service) will cause this error. 

Desc. Code

Description

1

You must enter a proper municipality/province combination or postal code.

1

Please provide a valid license key for this web service.

Additionally, requests made in the "rpc/encoded" format will cause this error.

The only namespace that should appear in any element is the www.serviceobjects.com on the root ValidateEmail element as so:
<GetGeoLocation xmlns="{+}https://www.serviceobjects.com/">

Important Note!
The namespace is not applied to the GetGeoLocation element, it is only present.


Error Code 2 – Various descriptions
This error code appears when various errors occur, but are of the expected nature. Oftentimes, maligned or incomplete input will cause an error 2. 

Desc. Code

Description

2

Please input a valid address.

2

Please input a valid postal code.

2

Location not found.

2

No Results Found.



Error Code 4 – Various descriptions
An error code 4 is a fatal error and it means something has seriously gone wrong. You will never see an error code 4 in a live production environment.

Frequently Asked Questions

The sample code is giving strange errors or keeps crashing!

Most likely, the sample code cannot connect to Service Objects. Many environments will not allow you to connect out on port 80, or will clip out XML data from these requests/responses. 

The easiest way to check for this is to open a browser on the machine running the sample code. In your browser, navigate to:
{+}https://trial.serviceobjects.com/gcc/
Then try to run one of the operations with your trial key. If you get a browser error, or get no data back, then the sample code isn't able to connect either. 

Contact your systems administrator to resolve why you are not able to connect to Service Objects.

DOTS Address Geocode – CA says that it cannot find my address!

DOTS Address Geocode – CA doesn't know about every address, especially empty lots or new streets. Often, it won't be able to find coordinates to these locations. We do our best to try to improve the data as often as possible. However, it will often be able to match a postal code. If it cannot match the exact street location, try the GetPostalCodeInfo operation to find how close it can find your data. 

We are constantly striving to improve our data! DOTS Address Geocode – CA may not be able to find your location now, but may in the future as we improve our databases.

I am not a programmer. How do I Use DOTS Address Geocode – CA?

Service Objects runs batches for you! A free batch trial is available at https://www.serviceobjects.com/batch/upload.

Do you also provide a RESTful interface?

Yes we do! For more information on how to use our RESTful interface go here DOTS Address Geocode - Canada - REST.

Conclusion

Service Objects is proud to offer you a free trial of DOTS Address Geocode – CA. 



Other technical questions or concerns can be directed to support@serviceobjects.com.

If you are interested in purchasing DOTS Address Geocode – US, please contact sales@serviceobjects.com.



  
We want to hear from you! We're always looking to improve our developer guides. 
Please email your suggestions to devguidefeedback@serviceobjects.com.

  • No labels