none
[SOLVED] Batch geocoding example fails to return successful link to geocoded data RRS feed

  • Question

  • Hi,

     

    I copied and pasted the code from http://msdn.microsoft.com/en-us/library/ff817006.aspx, actually declared $successUrl outside the scope of where it's declared in the code in order for it to be available later, and yet, despite, after about 60 seconds, the rather small job finishes, the code cannot find the successful url that it apparently is supposed to.

    Any ideas?

    Here's my output from the code they provided, with some echo's thrown in the mix to see what's going on.

     

     

    Job Created:
    Request Status: Created
    Job ID: fed5e8bd45ca45ce878d529e650a2671
    Job Status: Pending
    
    Checking status until complete...
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Pending
    about to check jobMyJob - Completed
    done checking
    set links
    successUrl: |in foreach
    |
    in foreach
    failed|
    
    Warning: file_get_contents(?output=xml&key=MYKEY) [function.file-get-contents]: failed to open stream: No error in C:\inetpub\wwwroot\...\geocodeexample.php on line 90
    
    Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\inetpub\wwwroot\...\geocodeexample.php:91 Stack trace: #0 C:\inetpub\wwwroot\NanaimoRCMPCrimeMap\geocodeexample.php(91): SimpleXMLElement->__construct('') #1 {main} thrown in C:\inetpub\wwwroot\...\geocodeexample.php on line 91

     

     

    Here's my full code listing in case it's useful...

     

     

    <html>
     <head>
     <title>Using the Bing Spatial Data Geocode Dataflow API</title>
     </head>
     <body>
     <?php
    
    error_reporting(E_ALL); ini_set('display_errors', '1');
    
    $key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    $url = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?description=MyJob&input=xml&output=xml&key=".$key;
    
    // STEP 1 - Create a geocode job
    
    // Get the contents of an XML data file
    $myfile = "geocodeFeed.xml";
    $data = file_get_contents($myfile);
    
    // This function constructs and sends an HTTP request with a provided URL and data, and returns an HTTP response object
    // This function uses the php_http extension 
    function do_post_request($url, $data, $optional_headers = null) 
    {
     $request = new HttpRequest($url, HttpRequest::METH_POST);
     $request->setBody($data);
     $response = $request->send();
     return $response->getBody();
    }
    
    // Call custom function to generate an HTTP request and get back an HTTP response
    $response = do_post_request($url, $data);
    
    // Convert the response body into an XML element so we can extract data
    $responseBody = new SimpleXMLElement($response);
    
    
    // Get data (such as job id, status description, and job status) from the response
    $statusDescription = $responseBody->StatusDescription;
    $jobId = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Id;
    $jobStatus = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Status;
    
    echo "Job Created:<br>";
    echo " Request Status: ".$statusDescription."<br>";
    echo " Job ID: ".$jobId."<br>";
    echo " Job Status: ".$jobStatus."<br><br>";
    
     
    // STEP 2 - Get the status of geocode job(s)
    
    // Call the API to determine the status of all geocode jobs associated with a Bing Maps key
    echo "Checking status until complete...<br>";
    while ($jobStatus != "Completed") {
    
     // Wait 5 seconds, then check the job’s status
     sleep(5);
    
     // Construct the URL to check the job status, including the jobId
     echo "about to check job";
     $checkUrl = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/".$jobId."?output=xml&key=".$key;
     $checkResponse = file_get_contents($checkUrl);
     $responseBody = new SimpleXMLElement($checkResponse);
    
     // Get and print the description and current status of the job 
     $jobDesc = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Description;
     $jobStatus = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Status;
    
     echo $jobDesc." - ".$jobStatus."<br>";
    
    }
    echo "done checking<br>";
    // STEP 3 - Obtain results from a successfully geocoded set of data
    
    //Iterate through the links provided with the first geocode job and extract the 'succeeded' link
    $Links = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Link;
    echo "set links<br>";
    $successUrl = "";
    echo "successUrl: " . $successUrl . "|";
    foreach ($Links as $Link) {
    echo "in foreach<br>";
    echo $Link['name'] . "|<br>";
     if ($Link['name'] == "succeeded") 
     { 
     	echo "in if";
     $successUrl = $Link; 
     break; 
     }
    }
    
    // Access the URL for the successful requests, and convert response to an XML element
    $successUrl .= "?output=xml&key=".$key;
    $successResponse = file_get_contents($successUrl);
    $successResponseBody = new SimpleXMLElement($successResponse);
    
    // Loop through the geocoded results and output addresses and lat/long coordinates
    foreach ($successResponseBody->GeocodeEntity as $entity) {
     echo $entity->GeocodeResponse->Address['FormattedAddress'],"<br>";
     if (!$entity->GeocodeResponse->RooftopLocation) {
     echo $entity->GeocodeResponse->InterpolatedLocation['Longitude'].", ";
     echo $entity->GeocodeResponse->InterpolatedLocation['Latitude']."<br>";
     }
     else {
     echo $entity->GeocodeResponse->RooftopLocation['Longitude'].", ";
     echo $entity->GeocodeResponse->RooftopLocation['Latitude']."<br>";
     }
    }
    
    ?>
    
     </body>
    </html>
    

     

    Thanks in advance for any suggestions!

     

    Kevin


    • Edited by kevin-berry Monday, May 30, 2011 3:30 PM
    • Moved by Ricky_Brundritt Friday, March 9, 2012 5:42 PM (From:Bing Maps: Map Control and Web services Development)
    Saturday, May 28, 2011 8:32 AM

Answers

  • I didn't see the input parameter the first time I looked at your code. I wouldn't put too much faith in that documentation you pointed to. In the middle of it it has a response from the routing service which has nothing to do with the Bing Spatial Data Services. I have a pretty good feeling who ever wrote that article didn't try running their code. 

    The content type should be specified though as it is possible for your xml file to be zipped which would change the content type. Information on the content type can be found in the official API documentation here: http://msdn.microsoft.com/en-us/library/ff701737.aspx If you read through there it says the you must specify the content type. Try something like this:

    $request->setContentType("application/xml")

     

     


    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Monday, May 30, 2011 11:40 AM
  • Not sure if you fixed this yet, but your Culture attribute appears to be invalid. The culture should be en-US
    Monday, May 30, 2011 1:19 PM

All replies

  • Have you been able to see the response either by using fiddler or by outputting it to the screen. Try getting the status URL and using that in a browser to see what the response is that is being returned. You can also try putting together a URL which will have this format:

    "https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/" + JobId +"/output/succeeded?output=xml&key=" + key

    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Saturday, May 28, 2011 9:46 AM
  • Hi,

    I did just what you said, and it appears the XML it gives me says:

    The requested resource was not found.

    Also, when I change the condition to "failed" rather than "success" I get this output:

     

    Job Created:
    Request Status: Created
    Job ID: bc0a01182796460daebe2ccc7fc9cbb3
    Job Status: Pending

    Checking status until complete...
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Completed
    done checking
    |
    failed|
    setting successUrlsuccessUrl: https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/bc0a01182796460daebe2ccc7fc9cbb3/output/failed|
    ,

    ,

    ,

     

     

    So obviously something is awry... but what? It tells me the job is completed, so I'm assuming that means it completed successfully, but if not... I'm not sure how to make sure it completes successfully.

     

    PS. I don't know what fiddler is. I'll look into that.


    Saturday, May 28, 2011 8:10 PM
  • When there is an issue you will either get a status of "Aborted" or "Completed" with a failure URL. The aborted status indicates an issue with the file being uploaded. Failure and success URLs have the geocoded results. The success url points to the data that geocoded successfully, where as the failure URL points to the data that did not geocode successfully, i.e. location not found. Only locations that are geocoded will be available through the success URL.  So in short, the issue is with your data that you are uploading. Is it possible to post a couple locations you are trying to geocode?
    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Saturday, May 28, 2011 10:47 PM
  • Here's the file that they supply on the website. I decided to go with their data when testing this before attempting to use my own (figured theirs worked, whereas I could be liable to screw up in the formatting of my own data).

     

    <GeocodeFeed>
      <GeocodeEntity Id="001"
                 xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US">
          <Address AddressLine="291 Broadway" AdminDistrict="NY" Locality="New York"
                   PostalCode="10007" />
        </GeocodeRequest>
      </GeocodeEntity>
      <GeocodeEntity Id="002"
                 xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US">
          <Address AddressLine="599 Broadway" AdminDistrict="NY" Locality="New York" />
          <ConfidenceFilter MinimumConfidence="High" xmlns="" />
        </GeocodeRequest>
      </GeocodeEntity>
      <GeocodeEntity Id="003"
                xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US" Query="Empire State Building" />
      </GeocodeEntity>
    </GeocodeFeed>

    Saturday, May 28, 2011 11:02 PM
  • Note: I should mention that despite such a small data set, my PHP timeout threshold of 60 seconds is often reached.. Haven't quite figured out why it takes so long.

     

    Also, this might be helpful:

     

    Job Created:
    Request Status: Created
    Job ID: 424321cd66ca404c897ec50a7f29b84b
    Job Status: Pending

    Checking status until complete...
    MyJob - Pending
    MyJob - Pending
    MyJob - Completed
    done checking

    Warning: file_get_contents(?output=xml&key=KEY) [function.file-get-contents]: failed to open stream: No error in C:\inetpub\wwwroot\...\geocodeexample.php on line 85

    Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\inetpub\wwwroot\...\geocodeexample.php:86 Stack trace: #0 C:\inetpub\wwwroot\...\geocodeexample.php(86): SimpleXMLElement->__construct('') #1 {main} thrown in C:\inetpub\wwwroot\...\geocodeexample.php on line 86

    Those errors were thrown with this as the feed:

     

    <GeocodeFeed>
      <GeocodeEntity Id="001"
                 xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US">
          <Address AddressLine="291 Broadway" AdminDistrict="NY" Locality="New York" />
        </GeocodeRequest>
      </GeocodeEntity>
    </GeocodeFeed>


    Saturday, May 28, 2011 11:15 PM
  • Ok, It will take more than 90 seconds on average for the Geocode process to occur. This is a batch process and is not meant to be used as an instant geocoding service. For that you would need to use the Bing Maps REST Geocode service and geocode each location, one at a time. The batch process is meant to be a long running process. When a job is created it goes into a queue and will be processed when it is it's turn. I've found y geocoding jobs can take anywhere from 1 - 20 minutes. Note that in the documentation it says it can take up to 24 hours. This all depends on how busy the server is and how much data I'm geocoding.  One of the primary purposes of this service is to geocode your data ahead of time so you can store it in a DB or in the Bing Spatial Data Services. If you just need to be able to goecode your data and aren't concerned with being able to do it through code check out the data uploader tool I created here: http://bingmapslocators.cloudapp.net/DataUploader 
    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Sunday, May 29, 2011 11:38 AM
  •  

    Hi there,

    Thanks for the heads up. I'll make sure to increase my execution timeout threshold. I'm still not sure why it's failing, however, and I need this solution to work. I've increased the max_execution_time to 3660 so I no longer get the execution-time exceeded error, but I'm still getting this output:

    Job Created:
    Request Status: Created
    Job ID: 087c2d4c12d948a29143b8fac90212f4
    Job Status: Pending

    Checking status until complete...
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Completed

    Warning: file_get_contents(?output=xml&key=KEY) [function.file-get-contents]: failed to open stream: No such file or directory in C:\inetpub\wwwroot\...\geocodeexample.php on line 82

    Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\inetpub\wwwroot\...\geocodeexample.php:83 Stack trace: #0 C:\inetpub\wwwroot\...\geocodeexample.php(83): SimpleXMLElement->__construct('') #1 {main} thrown in C:\inetpub\wwwroot\...\geocodeexample.php on line 83

    --------------------------------------------------

    For this feed:

    <GeocodeFeed>
      <GeocodeEntity Id="001"
                 xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US">
          <Address AddressLine="291 Broadway" AdminDistrict="NY" Locality="New York"
                   PostalCode="10007" />
        </GeocodeRequest>
      </GeocodeEntity>
      <GeocodeEntity Id="002"
                 xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US">
          <Address AddressLine="599 Broadway" AdminDistrict="NY" Locality="New York" />
          <ConfidenceFilter MinimumConfidence="High" xmlns="" />
        </GeocodeRequest>
      </GeocodeEntity>
      <GeocodeEntity Id="003"
                xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
        <GeocodeRequest Culture="en US" Query="Empire State Building" />
      </GeocodeEntity>
    </GeocodeFeed>

    --------------------------------------------------

    Using this code:

     

    <html>
     <head>
     <title>Using the Bing Spatial Data Geocode Dataflow API</title>
     </head>
     <body>
     <?php
    
    $key = "KEY";
    $url = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?description=MyJob&input=xml&output=xml&key=".$key;
    
    // STEP 1 - Create a geocode job
    
    // Get the contents of an XML data file
    $myfile = "geocodeFeed.xml";
    $data = file_get_contents($myfile);
    
    // Call custom function to generate an HTTP request and get back an HTTP response
    $response = do_post_request($url, $data);
    
    // This function constructs and sends an HTTP request with a provided URL and data, and returns an HTTP response object
    // This function uses the php_http extension 
    function do_post_request($url, $data, $optional_headers = null) {
     $request = new HttpRequest($url, HttpRequest::METH_POST);
     $request->setBody($data);
     $response = $request->send();
     return $response->getBody();
    }
    
    // Convert the response body into an XML element so we can extract data
    $responseBody = new SimpleXMLElement($response);
    
    
    // Get data (such as job id, status description, and job status) from the response
    $statusDescription = $responseBody->StatusDescription;
    $jobId = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Id;
    $jobStatus = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Status;
    
    echo "Job Created:<br>";
    echo " Request Status: ".$statusDescription."<br>";
    echo " Job ID: ".$jobId."<br>";
    echo " Job Status: ".$jobStatus."<br><br>";
    
     
    // STEP 2 - Get the status of geocode job(s)
    
    // Call the API to determine the status of all geocode jobs associated with a Bing Maps key
    echo "Checking status until complete...<br>";
    while ($jobStatus != "Completed") {
    
     // Wait 5 seconds, then check the job’s status
     sleep(5);
    
     // Construct the URL to check the job status, including the jobId
     $checkUrl = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/".$jobId."?output=xml&key=".$key;
     $checkResponse = file_get_contents($checkUrl);
     $responseBody = new SimpleXMLElement($checkResponse);
    
     // Get and print the description and current status of the job 
     $jobDesc = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Description;
     $jobStatus = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Status;
    
     echo $jobDesc." - ".$jobStatus."<br>";
    
    }
    
    // STEP 3 - Obtain results from a successfully geocoded set of data
    
    $successUrl="";
    
    //Iterate through the links provided with the first geocode job and extract the 'succeeded' link
    $Links = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Link;
    foreach ($Links as $Link) {
     if ($Link['name'] == "succeeded") 
     { 
     $successUrl = $Link; 
     break; 
     }
    }
    
    // Access the URL for the successful requests, and convert response to an XML element
    $successUrl .= "?output=xml&key=".$key;
    $successResponse = file_get_contents($successUrl);
    $successResponseBody = new SimpleXMLElement($successResponse);
    
    // Loop through the geocoded results and output addresses and lat/long coordinates
    foreach ($successResponseBody->GeocodeEntity as $entity) {
     echo $entity->GeocodeResponse->Address['FormattedAddress'],"<br>";
     if (!$entity->GeocodeResponse->RooftopLocation) {
     echo $entity->GeocodeResponse->InterpolatedLocation['Longitude'].", ";
     echo $entity->GeocodeResponse->InterpolatedLocation['Latitude']."<br>";
     }
     else {
     echo $entity->GeocodeResponse->RooftopLocation['Longitude'].", ";
     echo $entity->GeocodeResponse->RooftopLocation['Latitude']."<br>";
     }
    }
    
    ?>
    
     </body>
    </html>
    

     

    Any idea what's going wrong here?

    Thanks for your help thus far. Very much appreciated that you're taking the time to troubleshoot this with me.

     

    Kevin

     


    Sunday, May 29, 2011 8:33 PM
  • Can you add some code to print the checkURL. Then once it is complete try hitting that url in a browser and look at the content. You should see what the response is. If possible, post it here. You should be able to see if there is and url's; seuccess or failure, or an error.


    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Sunday, May 29, 2011 8:41 PM
  • Very interesting.... It's failing on all 3 ....

    <Response>
    <Copyright>
    Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.
    </Copyright>
    <BrandLogoUri>
    http://spatial.virtualearth.net/Branding/logo_powered_by.png
    </BrandLogoUri>
    <StatusCode>200</StatusCode>
    <StatusDescription>OK</StatusDescription>
    <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
    <TraceId>99a66bd3e20a425386bb2a1f7f3df88a|BAYM001573|02.00.115.900|</TraceId>
    <ResourceSets>
    	<ResourceSet>
    		<EstimatedTotal>1</EstimatedTotal>
    		<Resources>
    			<DataflowJob><Id>b1733116f2ea42b7b322c1140c11417c</Id>
    				<Link role="self">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/b1733116f2ea42b7b322c1140c11417c</Link>
    				<Link role="output" name="failed">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/b1733116f2ea42b7b322c1140c11417c/output/failed</Link>
    				<Description>MyJob</Description>
    				<Status>Completed</Status>
    				<CreatedDate>2011-05-29T14:07:57.4825357-07:00</CreatedDate>
    				<CompletedDate>2011-05-29T14:08:17.3107108-7:00</CompletedDate>
    				<TotalEntityCount>3</TotalEntityCount>
    				<ProcessedEntityCount>3</ProcessedEntityCount>
    				<FailedEntityCount>3</FailedEntityCount>
    			</DataflowJob>
    		</Resources>
    	</ResourceSet>
    </ResourceSets>
    </Response>
    

    Sunday, May 29, 2011 9:15 PM
  • have you tried specifying an input type? I don't see one in your code. I also don't see the file content type specified anywhere.
    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Sunday, May 29, 2011 9:23 PM
  • Well, that would probably solve my issue. I'll read the docs some more in case I glossed over that... but I thought the input/output type was taken care of in the URL: input=xml&output=xml

     

    Edit: I'm not seeing anything about those that you mention in the docs I'm reading http://msdn.microsoft.com/en-us/library/ff817006.aspx

    Sunday, May 29, 2011 9:26 PM
  • Hi Richard,

    I haven't been able to find what you're talking about in the documentation I looked at. Could you perhaps tell me how I'd go about adding that information into my code?

    Thanks!

    Kevin

    Monday, May 30, 2011 5:25 AM
  • I didn't see the input parameter the first time I looked at your code. I wouldn't put too much faith in that documentation you pointed to. In the middle of it it has a response from the routing service which has nothing to do with the Bing Spatial Data Services. I have a pretty good feeling who ever wrote that article didn't try running their code. 

    The content type should be specified though as it is possible for your xml file to be zipped which would change the content type. Information on the content type can be found in the official API documentation here: http://msdn.microsoft.com/en-us/library/ff701737.aspx If you read through there it says the you must specify the content type. Try something like this:

    $request->setContentType("application/xml")

     

     


    Windows Live Developer MVP - http://rbrundritt.wordpress.com | http://inknowledge.co.uk
    Monday, May 30, 2011 11:40 AM
  • Not sure if you fixed this yet, but your Culture attribute appears to be invalid. The culture should be en-US
    Monday, May 30, 2011 1:19 PM
  • *Jumps in elation* Thanks for the heads up about the culture type, John.

    And Richard, I added that line appropriately, and voila.... it did work.

    Thank you... so much. I wish I could buy you lunch or something... your help is going to let me get on with this project, and that's a great feeling.

    Thanks so much! (really, if there's something I can do for ya, let me know).

     

    Kevin

    Monday, May 30, 2011 3:30 PM
  • For those who may have the same issue I did, here's the final code:

    The XML Feed:

     

    <GeocodeFeed>
     <GeocodeEntity Id="001"
        xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
     <GeocodeRequest Culture="en-US">
      <Address AddressLine="291 Broadway" AdminDistrict="NY" Locality="New York"
        PostalCode="10007" />
     </GeocodeRequest>
     </GeocodeEntity>
     <GeocodeEntity Id="002"
        xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
     <GeocodeRequest Culture="en-US">
      <Address AddressLine="599 Broadway" AdminDistrict="NY" Locality="New York" />
      <ConfidenceFilter MinimumConfidence="High" xmlns="" />
     </GeocodeRequest>
     </GeocodeEntity>
     <GeocodeEntity Id="003"
       xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">
     <GeocodeRequest Culture="en-US" Query="Empire State Building" />
     </GeocodeEntity>
    </GeocodeFeed>
    
    The code:

     

     

    <html>
     <head>
     <title>Using the Bing Spatial Data Geocode Dataflow API</title>
     </head>
     <body>
     <?php
    
    $key = "Bing Maps Key";
    $url = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?description=MyJob&input=xml&output=xml&key=".$key;
    
    // STEP 1 - Create a geocode job
    
    // Get the contents of an XML data file
    $myfile = "geocodeFeed.xml";
    $data = file_get_contents($myfile);
    
    // Call custom function to generate an HTTP request and get back an HTTP response
    $response = do_post_request($url, $data);
    
    // This function constructs and sends an HTTP request with a provided URL and data, and returns an HTTP response object
    // This function uses the php_http extension 
    function do_post_request($url, $data, $optional_headers = null) {
     $request = new HttpRequest($url, HttpRequest::METH_POST);
     $request->setBody($data);
     $request->setContentType("application/xml");
     $response = $request->send();
     return $response->getBody();
    }
    
    // Convert the response body into an XML element so we can extract data
    $responseBody = new SimpleXMLElement($response);
    
    
    // Get data (such as job id, status description, and job status) from the response
    $statusDescription = $responseBody->StatusDescription;
    $jobId = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Id;
    $jobStatus = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Status;
    
    echo "Job Created:<br>";
    echo " Request Status: ".$statusDescription."<br>";
    echo " Job ID: ".$jobId."<br>";
    echo " Job Status: ".$jobStatus."<br><br>";
    
     
    // STEP 2 - Get the status of geocode job(s)
    
    // Call the API to determine the status of all geocode jobs associated with a Bing Maps key
    echo "Checking status until complete...<br>";
    while ($jobStatus != "Completed") {
    
     // Wait 5 seconds, then check the job’s status
     sleep(5);
    
     // Construct the URL to check the job status, including the jobId
     $checkUrl = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/".$jobId."?&output=xml&key=".$key;
     $checkResponse = file_get_contents($checkUrl);
     $responseBody = new SimpleXMLElement($checkResponse);
    
     // Get and print the description and current status of the job 
     $jobDesc = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Description;
     $jobStatus = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Status;
    
     echo $jobDesc." - ".$jobStatus."<br>";
    }
    
    echo "checkUrl: " . $checkUrl . "<br>";
    
    // STEP 3 - Obtain results from a successfully geocoded set of data
    
    $successUrl="";
    
    //Iterate through the links provided with the first geocode job and extract the 'succeeded' link
    $Links = $responseBody->ResourceSets->ResourceSet->Resources->DataflowJob->Link;
    foreach ($Links as $Link) {
     if ($Link['name'] == "succeeded") 
     { 
     $successUrl .= $Link; 
     break; 
     }
    }
    
    // Access the URL for the successful requests, and convert response to an XML element
    $successUrl .= "?output=xml&key=".$key;
    $successResponse = file_get_contents($successUrl);
    $successResponseBody = new SimpleXMLElement($successResponse);
    
    // Loop through the geocoded results and output addresses and lat/long coordinates
    foreach ($successResponseBody->GeocodeEntity as $entity) {
     echo $entity->GeocodeResponse->Address['FormattedAddress'],"<br>";
     if (!$entity->GeocodeResponse->RooftopLocation) {
     echo $entity->GeocodeResponse->InterpolatedLocation['Longitude'].", ";
     echo $entity->GeocodeResponse->InterpolatedLocation['Latitude']."<br>";
     }
     else {
     echo $entity->GeocodeResponse->RooftopLocation['Longitude'].", ";
     echo $entity->GeocodeResponse->RooftopLocation['Latitude']."<br>";
     }
    }
    
    ?>
    
     </body>
    </html>
    

     

    The Output:

    Job Created:
    Request Status: Created
    Job ID: 15702ecbc3724f3eb4a67dd48962b20e
    Job Status: Pending

    Checking status until complete...
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Pending
    MyJob - Completed
    checkUrl: http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/15702ecbc3724f3eb4a67dd48962b20e?&output=xml&key=AlFh4_XMKnLnvK1XEP2Dny75N88a0UNtl9krISHp0WTe7WSYsNak6KjndXolidaT
    291 Broadway, New York, NY 10007-1814
    -74.006134, 40.715
    599 Broadway, New York, NY 10012-3235
    -73.99702, 40.725111
    Empire State Building, NY
    -73.98581, 40.748435

     


    • Edited by Ricky_Brundritt Monday, May 30, 2011 5:17 PM removing Bing maps Key
    Monday, May 30, 2011 3:33 PM