<?php

// ---------------------------------------------------------
// 
// WMS2KML - A Google Earth(tm) WMS Publisher
//
// Version 0.1
//
// ---------------------------------------------------------
//
// This script publishes a known OGC WMS 1.1.1 service into
// Google Earth KML format using the KML 2.1 Region feature,
// allowing for efficient scale-dependant image serving.
//
// ---------------------------------------------------------
//
// Copyright 2006 Jason Birch
// http://www.jasonbirch.com/nodes/
//
// This application is made available under the terms of
// the Creative Commons "Attribution-Sharealike 2.5" license
// a copy of which can be found here:
// http://creativecommons.org/licenses/by-sa/2.5/
//
// Please feel free to copy and modify the included code
// under the above-stated license, but ensure that you
// attribute the work, citing my name and web site.
//
// Google Earth is a trademark of Google Inc.
//
// ---------------------------------------------------------

// User-definable variables

   // Set to the location of this script
   
$myUrl "http://localhost/wms2kml.php";

   
// Set to a user-defined title for the document and initial folder.
   
$docName "WMS2KML Document";

   
// Set to True or False depending on whether you want the Region hierarchy shown:
   
$hideHierarchy True;

   
// Set the initial request rectangle for the WMS server
   
$INIT["north"] = 49.3;
   
$INIT["south"] = 25.2;
   
$INIT["east"] = -69.1;
   
$INIT["west"] = -123.5;

   
// Set the image tile dimensions in pixels.  Should be in proportion to the
   // initial request rectangle for best performance.
   
$WMS["width"] = 512;
   
$WMS["height"] = 227;

   
// Set the image format.  Google Earth likes GIF
   
$WMS["format"] = "image/gif";

   
// For services that support it, transparency is recommended
   
$WMS["transparent"] = "TRUE";

   
// Base URL and Layers (if multiple, separate with commas) for WMS service
   
$WMS["baseUrl"] = "http://example.org/path/to/wms.cgi?";
   
$WMS["layers"] = "layer1,layer2";

   
// Can just leave blank, or match to above line (one per layer)
   
$WMS["styles"] = "";


// You shouldn't have to tweak the script much below this line

// ------------------------------------------------------------------------


   // This function creates a KML Region that links to a single WMS service
   // with an image  bounding box identical to the Region's extents.

   
function createWmsRegion($url$north$south$east$west)
   {

      
$retval '
   <NetworkLink>
      <visibility>1</visibility>
      <Region>
         <LatLonAltBox>
            <north>'
.$north.'</north>
            <south>'
.$south.'</south>
            <east>'
.$east.'</east>
            <west>'
.$west.'</west>
         </LatLonAltBox>
         <Lod>
             <minLodPixels>380</minLodPixels>
             <maxLodPixels>-1</maxLodPixels>
         </Lod>
      </Region>
      <Link>
         <viewRefreshMode>onRegion</viewRefreshMode>
         <href>'
.$url.'?DBOX='.$west.','.$south.','.$east.','.$north.'</href>
      </Link>
   </NetworkLink>'
;

      return 
$retval;
     
   }


   
$outString '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
   <NetworkLinkControl>
      <minRefreshPeriod>3600</minRefreshPeriod>
   </NetworkLinkControl> -->
'
;


   
// If this file is being called from itself, the DBOX key will exist

    
if (array_key_exists('DBOX'$_GET))
    {

        
$coords preg_split('/,|\s/'$_GET['DBOX']);
        
$CURR["west"] = (float) $coords[0];
        
$CURR["south"] = (float) $coords[1];
        
$CURR["east"] = (float) $coords[2];
        
$CURR["north"] = (float) $coords[3];

      
$baseurl $WMS["baseUrl"].'service=wms&amp;version=1.1.1&amp;request=GetMap&amp;srs=EPSG:4326&amp;width='.$WMS["width"].'&amp;height='.$WMS["height"].'&amp;format='.$WMS["format"].'&amp;transparent='.$WMS["transparent"].'&amp;layers='.$WMS["layers"].'&amp;styles='.$WMS["styles"];
   

      
// Output the image link for the current extents

      
$outString .= '<GroundOverlay>
  <drawOrder>1</drawOrder>
  <Icon>
    <href>'
.$baseurl.'&amp;bbox='.$CURR["west"].','.$CURR["south"].','.$CURR["east"].','.$CURR["north"].'</href>
  </Icon>
  <LatLonBox>
    <north>'
.$CURR["north"].'</north>
    <south>'
.$CURR["south"].'</south>
    <east>'
.$CURR["east"].'</east>
    <west>'
.$CURR["west"].'</west>
  </LatLonBox>
</GroundOverlay>
'
;


      
// Set up the coordinates for the extents and the mid value in each dimension

      
$xval[0] = $CURR["west"];
      
$xval[1] = $CURR["west"] - ($CURR["west"] - $CURR["east"]) / 2;
      
$xval[2] = $CURR["east"];
   
      
$yval[0] = $CURR["south"];
      
$yval[1] = $CURR["south"] - ($CURR["south"] - $CURR["north"]) / 2;
      
$yval[2] = $CURR["north"];
   
      
// Access the previous bounding coordinates for each of the four cells in the quad

      
for ($x 0$x <= 1$x++) 
      {
         for (
$y 0$y <= 1$y++) 
         {
            
$outString .= createWmsRegion($myUrl$yval[$y 1], $yval[$y], $xval[$x 1], $xval[$x]);
         }
      }
   }
   else
   {  

      
// This is the initial setup for the first time the network link is loaded

      
$outString .= '<name>'.$docName.'</name>
'
;
      
$outString .= '<Folder>
   <name>'
.$docName.'</name>';

      if (
$hideHierarchy)
      {
         
$outString .= '<Style>
      <ListStyle>
         <listItemType>checkHideChildren</listItemType>            
      </ListStyle>          
   </Style>
'
;
      }

      
// Generate a network link for the initial full-extent region
      
$outString .= createWmsRegion($myUrl$INIT["north"], $INIT["south"], $INIT["east"], $INIT["west"]);

      
$outString .= '</Folder>
'
;

   }



   
$outString .= '</Document>
</kml>
'
;

   
// Send the KML header and the KML contents.  Swap the two header lines for debugging in browser.

   
header("Content-Type: application/vnd.google-earth.kml+xml");
//   header("Content-Type: text/xml");
   
print($outString);

?>