Jayant's Blog

Wednesday, August 13, 2008

Using Php with ArcGIS Server 9.3 REST (v0.03)

So here's another sample. I have a pre-populated JSON file (addresses.txt) with a bunch of addresses to be geocoded.

{
  "addresses": [
    { "name":"ESRI", "street":"380 New York St", "city":"Redlands", "state":"CA", "zip":92373 },
    { "name":"Google", "street":"1600 Amphitheatre Parkway", "city":"Mountain View", "state":"CA", "zip":94043 },
    { "name":"Yahoo", "street":"701 First Avenue", "city":"Sunnyvale", "state":"CA", "zip":94089 },
    { "name":"Microsoft", "street":"One Microsoft Way", "city":"Redmond", "state":"WA", "zip":98052 }
  ]
}


This code shows how to load up the address list from the JSON file. I tried naming the file as .json, but am guessing since my json mime-type has not been set correctly, it wasn't loaded properly.

<?php
$url = "addresses.txt";
$response = file_get_contents($url);
$json = json_decode($response);
?>

Next is the code to take the address, build the request and use the geocoding service on sample server to geocode the addresses.

<?php
$geocodeUrl = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/" . "Locators/ESRI_Geocode_USA/GeocodeServer/" . "findAddressCandidates?f=json";
foreach($json->addresses as $address) {
  $url = str_replace(" ", "+", $geocodeUrl . "&Address=" . $address->street . "&City=" . $address->city . "&State=" . $address->state . "&Zip=" . $address->zip);

  $response = file_get_contents($url);
  $candidates = json_decode($response);
?>

Next filter the address candidates and display only those candidates who's score is 100. We simply print these.

<?php
  $html = "Address candidate(s) for (" . $address->name . "\n<ul>\n";
  foreach($candidates->candidates as $candidate) {
    if ($candidate->score == 100) {
      $html .= "<li>" . $candidate->address . " (" . $candidate->location->x . ", " . $candidate->location->y . ")</li>";
    }
  }
  $html .= "</ul>\n";
  echo $html;
}
?>

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home