<?

/**
 * $Project: nearby $
 * 
 * Version 2 (16/08/2006)
 *   added gisdata.usgs.net lookup thanks to Lowell Stewart!
 * Version 2.1 (06/01/2007)
 *   added geonames srtm3 lookup
 * 
 * This file copyright (C) 2007 Barry Hunter (nearby@barryhunter.co.uk)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */


if ($_FILES['userfile']) {

    if (
is_uploaded_file($_FILES['userfile']['tmp_name'])) {
       
//ok to continue!
    
} else {
       echo 
"Error Uploading File [Either currupted in transit, no file selected, or file was too big (> 30kb)]: ";
       echo 
"filename '"$_FILES['userfile']['name'] . "'.";
       exit;
    }

    
$filename str_replace('.kml',"-filled.kml",basename($_FILES['userfile']['name']));

    
$kml file_get_contents($_FILES['userfile']['tmp_name']);

    
preg_match_all('/([\s >\n\t]+)(-?\d+[\.\d]*),(-?\d+[\.\d]*),('.$_POST['zero'].')\b/',$kml,$m);

    
$c 1;
    foreach (
$m[0] as $i => $full) {
        if (!
$done["{$m[3][$i]}/{$m[2][$i]}"] && $c 100) {
            
$height 'Unknown';
            if (
$_POST['service'] == 'geonamessrtm') {
                
$url "http://ws.geonames.org/srtm3?lat={$m[3][$i]}&lng={$m[2][$i]}";
                
$height = @file_get_contents($url);
                
$height trim($height);
                if (
$height == -32768)
                    
$height 'Unknown';
            } elseif (
$_POST['service'] == 'geonames') {
                
$url "http://ws.geonames.org/gtopo30?lat={$m[3][$i]}&lng={$m[2][$i]}";
                
$height = @file_get_contents($url);
                
$height trim($height);
            } elseif (
$_POST['service'] == 'earthtools') {
                
#http://www.earthtools.org/height/<latitude>/<longitude>
                
$url "http://www.earthtools.org/height/{$m[3][$i]}/{$m[2][$i]}";
                
$file = @file_get_contents($url);
                if (
preg_match('/<meters>(-?\d+)<\/meters>/',$file,$o)) {
                    
$height $o[1];
                }
            } elseif (
$_POST['service'] == 'usgs') { 
                
$url "http://gisdata.usgs.net/XMLWebServices/TNM_Elevation_Service.asmx/getElevation?X_Value={$m[2][$i]}&Y_Value={$m[3][$i]}&Elevation_Units=METERS&Source_Layer=-1&Elevation_Only=TRUE";                
                
$file = @file_get_contents($url); 
                if (
preg_match('/>(-?\d+[\.\d]*)<\/string>/',$file,$o)) { 
                    
$height $o[1]; 
                }
            } 

            if (
$height == 'Unknown')
                
$height = -9999;
            
$kml str_replace("{$m[2][$i]},{$m[3][$i]},{$_POST['zero']}","{$m[2][$i]},{$m[3][$i]},$height",$kml);

            
sleep(1);
        }
        
$done["{$m[2][$i]}/{$m[1][$i]}"]++;
        
$c++;
    }


    
######################################

    
header("Content-type: application/vnd.google-earth.kml+xml");
    
header("Content-Disposition: attachment; filename=\"$filename\"");

    print 
$kml;

    
######################################

    
exit;


?>

<title>KML Altitude Filler (v2.1)</title>
<script>
function autoDisable(that) {
     that.value = "Submitting... Please wait...";
     name = "document."+that.form.name+"."+that.name;
  
     setTimeout(name+".disabled = true",100); //if we disable in the function then form wont submit
     setTimeout(name+".value="+name+".defaultValue; "+name+".disabled = false",30000);
     return true;
}</script>
<body style="font-family:arial">
<p align=right>Brought to you by <a href="http://www.nearby.org.uk/">nearby.org.uk</a>.</p>

<h2>KML Altitude Filler (v2.1)</h2>

<p><b>Please select the KML file you would like to add alitude for, subject to the following restrictions*:</b></p>


<ul>
<li><b>30kb limit</b> on file uploaded, to avoid killing the server</li>
<li>will only understand (and produce) <B>KML</B> files, rather than KMZ. (if you have a kmz just open it in a zip program and extract the doc.kml file)</li>
<li>will only add altitude to the first 100 points/path points. run the file though this page again to add further points</li>
<li>if the webservice doesnt return a valid alitude then will put -9999 into the height field</li>
</ul>


<form enctype="multipart/form-data" action="elevation-kml.php?submitted=1" method="POST" style="background-color:#dddddd; border:1px solid black; padding:10px; width:650px" name="form1">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    KML File: <input name="userfile" type="file" size="60"/><br/><br/>
    WebService to use: <br/>
    <input name="service" value="geonamessrtm" type="radio" checked/> <a href="http://www.geonames.org/export/#ws">geonames.org SRTM3</a> (Worldwide: SRTM data, 90m grid spacing)<br/>
    <input name="service" value="geonames" type="radio"/> <a href="http://www.geonames.org/export/#ws">geonames.org GTOPO30</a> (Worldwide: GTOPO30 data, 1km grid spacing)<br/>
    <input name="service" value="earthtools" type="radio" /> <a href="http://www.earthtools.org/webservices.htm">earthtools.org</a> (US & Europe: SRTM data, 90m grid spacing)
    <br/><input name="service" value="usgs" type="radio" /> <a href="http://gisdata.usgs.net/XMLWebServices/TNM_Elevation_Service.php">gisdata.usgs.net</a> (Worldwide, various spacing)
    <br/><br/>
    'Zero' Altitude to replace: <input name="zero" type="text" size="2" value="0"/><br/>
    <small>(use if you have a constant alititude to replace)</small><br/><br/>
    <input name="submitt" type="submit" value="Send File" onclick="autoDisable(this)"/>
    
    <p style="background-color:pink;padding:10px"><small><b>Takens on average 2 seconds per point (deliberatly slowed down!), so please be patient, and only click the Send button <u>once</u>.</b></small></p>
    
</form>

<p><small>* However with enough interest will consider lifting any of these restrictions, but might add output as KMZ to save bandwidth, but that will be transparent to you, the end user.</small></p> 


<p style="color:red"><small>*** <b>It works for <A HREF="mailto:nearby_REMOVE_@barryhunter.co.uk">me</a> but your mileage may vary! Use at your own risk, no guarantee is offered.</b> ***</small></p>