[Mapbender-commits] r9163 - in trunk/mapbender: http/classes http/extensions http/javascripts http/php http/plugins lib

svn_mapbender at osgeo.org svn_mapbender at osgeo.org
Mon Mar 9 05:43:13 PDT 2015


Author: syed
Date: 2015-03-09 05:43:13 -0700 (Mon, 09 Mar 2015)
New Revision: 9163

Modified:
   trunk/mapbender/http/classes/class_connector.php
   trunk/mapbender/http/classes/class_kml_ows.php
   trunk/mapbender/http/classes/class_kml_parser_ows.php
   trunk/mapbender/http/extensions/togeojson.js
   trunk/mapbender/http/extensions/togpx.js
   trunk/mapbender/http/extensions/tokml.js
   trunk/mapbender/http/javascripts/mod_savewmc.js
   trunk/mapbender/http/javascripts/mod_savewmc.php
   trunk/mapbender/http/php/kmlToGeoJSON.php
   trunk/mapbender/http/php/mb_metadata_uploadLayerPreview.php
   trunk/mapbender/http/php/mod_GetPublishedData.php
   trunk/mapbender/http/php/transformgeojson.php
   trunk/mapbender/http/php/uploadKml.php
   trunk/mapbender/http/plugins/kmlTree.js
   trunk/mapbender/http/plugins/mb_digitize_widget.php
   trunk/mapbender/http/plugins/mb_loadkmlgeorss.js
   trunk/mapbender/lib/mb.ui.displayKmlFeatures.js
Log:
add metadata for featureCollection and fix import-export functionality

Modified: trunk/mapbender/http/classes/class_connector.php
===================================================================
--- trunk/mapbender/http/classes/class_connector.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/classes/class_connector.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -1,7 +1,7 @@
 <?php
 # $Id$
 # http://www.mapbender.org/index.php/class_connector
-# Copyright (C) 2002 CCGIS 
+# Copyright (C) 2002 CCGIS
 #
 # 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
@@ -21,12 +21,12 @@
 /**
  * Establishes a connection to a given URL (and loads the content).
  * Supports HTTP (GET and POST), cURL and socket connections.
- * 
+ *
  * @class
  */
 class connector {
 
-	var $file;	
+	var $file;
 	private $connectionType;
 	private $timeOut = 20;
 	private $httpType = "get";
@@ -37,8 +37,8 @@
 	private $curlSendCustomHeaders = true; //decide to send own headers or not
 	private $curlCookiesession = true;
 	private $externalHeaders = "";
-	
-		
+
+
 	/**
 	 * @constructor
 	 * @param String url the URL that will be loaded (optional)
@@ -59,19 +59,20 @@
 			}
 		}
 	}
-	
+
 	/**
 	 * Loads content from the given URL.
 	 */
 	public function load($url) {
-		//some firewalls have problems to allow requests from a server behind it to the same server through 
-		//an internet connection. It can be that some requests are done thru this class to the urls of 
-		//HTTP_AUTH_PROXY or OWSPROXY. If some of those are part of the url they must be exchanged with 127.0.0.1 - 			//which hopefully should work. 
-		//TODO: check if http is ok for all 
+		//some firewalls have problems to allow requests from a server behind it to the same server through
+		//an internet connection. It can be that some requests are done thru this class to the urls of
+		//HTTP_AUTH_PROXY or OWSPROXY. If some of those are part of the url they must be exchanged with 127.0.0.1 - 			//which hopefully should work.
+		//TODO: check if http is ok for all
 		$posPROXY = strpos($url,OWSPROXY);
 		//$e = new mb_exception('class_connector: old url: '.$url);
  		if($posPROXY !== false && OWSPROXY_USE_LOCALHOST == true){
-			$e = new mb_notice('class_connector: old url: '.$url);	
+		var_dump('test1');die;
+			$e = new mb_notice('class_connector: old url: '.$url);
 			$url = str_replace($_SERVER['HTTP_HOST'], "127.0.0.1", $url);
 			$url = str_replace("https", "http", $url);//localhost no https should needed - it will be faster without
 			$e = new mb_notice('class_connector: new url: '.$url);
@@ -79,11 +80,13 @@
 
 		$e = new mb_notice('class_connector: load url: '.$url);
 		if (!$url) {
+		var_dump('test2');die;
 			$e = new mb_exception("connector: no URL given");
 			return false;
 		}
 		switch ($this->connectionType) {
 			case "curl":
+		var_dump('test3');die;
 			    if (func_num_args() == 2) {
             			$auth = func_get_arg(1);
 						if (isset($auth)) {
@@ -92,26 +95,31 @@
 						}
 				}
 				else {
+		var_dump('test4');die;
 				$e = new mb_notice("connector: curl without auth");
 					$this->file = $this->getCURL($url);
 				}
 				break;
 			case "http":
+		// var_dump('test5');
 			$e = new mb_notice("connector: http");
 				$this->file = $this->getHTTP($url);
+		// var_dump($this->getHTTP($url));
 				break;
 			case "socket":
+		var_dump('test6');die;
 			$e = new mb_notice("connector: socket");
 				$this->file = $this->getSOCKET($url);
 				break;
 		}
 		if(!$this->file){
+		// var_dump('test7');die;
 			$e = new mb_exception("connector: unable to load: ".$url);
 			return false;
 		}
-		return $this->file;		
+		return $this->file;
 	}
-	
+
 	/**
 	 * Sets the environment variables. The following can be set:
 	 * - connectionType ("http", "curl", "socket")
@@ -125,7 +133,7 @@
 					$this->connectionType = $value;
 				}
 				break;
-				
+
 			case "httpVersion":
 				if (in_array($value, array("1.0", "1.1"))) {
 					$this->httpVersion = $value;
@@ -134,7 +142,7 @@
 					$e = new mb_exception("class_connector.php: invalid http type '" . $value . "'");
 				}
 				break;
-							
+
 			case "httpType":
 				if (in_array(mb_strtoupper($value), array("POST", "GET"))) {
 					$this->httpType = $value;
@@ -143,35 +151,35 @@
 					$e = new mb_exception("class_connector.php: invalid http type '" . $value . "'");
 				}
 				break;
-			
+
 			case "httpPostData":
 				$this->httpPostData = $value;
 				break;
 
 			case "httpPostFieldsNumber":
 				$this->httpPostFieldsNumber = $value;
-				break;	
-	
+				break;
+
 			case "curlSendCustomHeaders":
 				$this->curlSendCustomHeaders = $value;
 				break;
-	
+
 			case "timeOut":
 				$this->timeOut = (integer)$value;
-				break;	
+				break;
 
 			case "externalHeaders":
 				$this->externalHeaders = $value;
-				break;	
-	
+				break;
+
 			case "httpContentType":
 				if ($this->isValidHttpContentType($value)) {
 					$this->httpContentType = $value;
 				}
 				break;
 		}
-	}	
-	
+	}
+
 	private function isValidConnectionType ($value) {
 		if (in_array(mb_strtoupper($value), array("HTTP", "CURL", "SOCKET"))) {
 			return true;
@@ -181,7 +189,7 @@
 			return false;
 		}
 	}
-	
+
 	private function isValidHttpContentType ($value) {
 		$validHttpContentTypeArray = array("XML","TEXT/XML","APPLICATION/XML","MULTIPART/FORM-DATA");
 		if (in_array(mb_strtoupper($value), $validHttpContentTypeArray)) {
@@ -197,7 +205,7 @@
 			return false;
 		}
 	}
-	
+
 	private function getCURL($url){
 		//urls should begin with http ;-)
 		$url=ltrim($url);
@@ -205,7 +213,7 @@
 		$url=str_replace(";","%3B",$url);
 		if (func_num_args() == 2) {
 			$auth = func_get_arg(1);
-		} //auth should be an array of ['username', 'realm', 'password', 'auth_type'] - or false - problem would be, that these are stored without hashing them! 
+		} //auth should be an array of ['username', 'realm', 'password', 'auth_type'] - or false - problem would be, that these are stored without hashing them!
 		$ch = curl_init ($url);
 		curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); //for images
 		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
@@ -221,20 +229,20 @@
 		//$host = parse_url($url,PHP_URL_HOST);
 		$arURL = parse_url($url);
 		$host = $arURL["host"];
-		$port = $arURL["port"]; 
+		$port = $arURL["port"];
 		if($port == ''){
 			$port = 80;
 			if($arURL["scheme"] == "https"){
 				$port = 443;
-			}	
+			}
 		}
-		
+
 		$path = $arURL["path"];
-		
+
 		// fill array (HOSTs not for Proxy)
 		$e = new mb_notice("class_connector.php: NOT_PROXY_HOSTS:".NOT_PROXY_HOSTS);
  	    	$NOT_PROXY_HOSTS_array = explode(",", NOT_PROXY_HOSTS);
- 	    
+
  	    	//check if http_proxy is set as env, if yes, unset it for the curl action here, it will be reset somewhere below - normally not needed, cause it will be only available when at execution time of the script http://php.net/manual/en/function.putenv.php
 		if (getenv('http_proxy')) {
 			$e = new mb_notice("class_connector.php: current http_proxy: ".getenv('http_proxy')." will be unset by putenv('http_proxy')");
@@ -251,26 +259,26 @@
 			curl_setopt($ch, CURLOPT_PROXY,CONNECTION_PROXY.":".CONNECTION_PORT);
 			$e = new mb_notice("class_connector.php: Proxy will be used!");
 			if(CONNECTION_PASSWORD != ""){
-				curl_setopt ($ch, CURLOPT_PROXYUSERPWD, CONNECTION_USER.':'.CONNECTION_PASSWORD);	
+				curl_setopt ($ch, CURLOPT_PROXYUSERPWD, CONNECTION_USER.':'.CONNECTION_PASSWORD);
 			}
 		} else {
 			$e = new mb_notice("class_connector.php: Proxy will not be used!");
-		}		
+		}
 		//TODO maybe allow basic authentication for client, but this will store the passwords in plain text
 		//TODO: store the  passwords as digest hash. Therefor we have to handle the realm which is defined in the 401 header and return it back to the scripts like mod_loadwms.php to store the digest into the database - problem: curl cannot handle digest connection without clear username and password - we have to send our own headers
-		if(isset($auth) && $auth != false) {	
+		if(isset($auth) && $auth != false) {
 			curl_setopt($ch, CURLOPT_USERPWD, $auth['username'].':'.$auth['password']);
 			if ($auth['auth_type'] == 'digest') {
-				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);	
+				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
 			}
 			if ($auth['auth_type'] == 'basic') {
 				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 			}
 		}
-		
-		
-		
-		//if httpType is POST, set CURLOPT_POST and CURLOPT_POSTFIELDS  
+
+
+
+		//if httpType is POST, set CURLOPT_POST and CURLOPT_POSTFIELDS
 		//and set a usefull http header
 		if(strtoupper($this->httpType) == 'POST'){
 			$headers = array(
@@ -279,11 +287,11 @@
            				"Cache-Control: no-cache",
 	           		 	"Pragma: no-cache",
 	           		 	"Content-length: ".strlen($this->httpPostData)
-			); 
-			$e = new mb_notice("connector: CURL POST: ".$this->httpPostData); 
+			);
+			$e = new mb_notice("connector: CURL POST: ".$this->httpPostData);
 			$e = new mb_notice("connector: CURL POST length: ".strlen($this->httpPostData));
-			
-			if ($this->curlSendCustomHeaders) {			
+
+			if ($this->curlSendCustomHeaders) {
 				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 			}
 			if ($this->httpPostFieldsNumber != 1){
@@ -291,7 +299,7 @@
 			} else {
 				curl_setopt($ch, CURLOPT_POST, 1);
 			}
-			curl_setopt($ch, CURLOPT_POSTFIELDS, $this->httpPostData);	
+			curl_setopt($ch, CURLOPT_POSTFIELDS, $this->httpPostData);
 			//$e = new mb_exception($this->httpPostData);
 		}
 		$useragent=CONNECTION_USERAGENT;
@@ -311,11 +319,11 @@
 		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 		}
 		#curl_setopt($ch, CURLOPT_HEADER, true);
-		$e = new mb_notice("class_connector.php: CURL connect to:".$url); 
+		$e = new mb_notice("class_connector.php: CURL connect to:".$url);
 		//curl_setopt ($ch,CURLOPT_USERAGENT,$useragent);
 		curl_setopt($ch,CURLOPT_DNS_USE_GLOBAL_CACHE, false);
 		curl_setopt($ch,CURLINFO_HEADER_OUT, true);
-		curl_setopt($ch, CURLOPT_FORBID_REUSE, false); 
+		curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
 		//curl_setopt ($ch,HTTPPROXYTUNNEL, 1);
 		//curl_setopt ($ch,CURLOPT_AUTOREFERER, 1);
 		//curl_setopt ($ch,CURLOPT_VERBOSE, true);
@@ -347,12 +355,13 @@
 		//reset the env variable http_proxy to the former value
 		if ($tmpHttpProxy != '') {
 			putenv("http_proxy=$tmpHttpProxy");
-		}	
+		}
 		$e = new mb_notice("class_connector.php: CURL give back: ".$file);
-		return $file;	
+		return $file;
 	}
 
 	private function getHTTP($url){
+			// var_dump(file_get_contents($url));die;
 		if ($this->httpType == "get") {
 			return @file_get_contents($url);
 	 	}
@@ -362,20 +371,20 @@
 			$urlComponentArray = parse_url($url);
 			$scheme = $urlComponentArray["scheme"];
 			$host = $urlComponentArray["host"];
-			$port = $urlComponentArray["port"]; 
+			$port = $urlComponentArray["port"];
 			if ($port == "") {
 				if ($scheme == "https") {
 					$port = 443;
 				}
 				else {
-					$port = 80;		
+					$port = 80;
 				}
-			}	
+			}
 			$path = $urlComponentArray["path"];
 			$query = $urlComponentArray["query"];
 			$buf = '';
 			if ($scheme == "https") {
-				$fp = fsockopen("ssl://". $host, $port, $errno, $errstr);				
+				$fp = fsockopen("ssl://". $host, $port, $errno, $errstr);
 			}
 			else {
 			    $fp = fsockopen($host, $port);
@@ -384,11 +393,11 @@
 			$postPath = "POST " . $path . "?" . $query . " HTTP/".$this->httpVersion . "\r\n";
 			$postStr .= $postPath;
 		    fputs($fp, $postPath);
-			
+
 			$postHost = "Host: " . $host . "\r\n";
 			$postStr .= $postHost;
 		    fputs($fp, $postHost);
-			
+
 		    if ($this->isValidHttpContentType($this->httpContentType)) {
 				$postContentType = "Content-type: " . $this->httpContentType . "\r\n";
 				$postStr .= $postContentType;
@@ -397,7 +406,7 @@
 			$postContentLength = "Content-length: " . strlen($this->httpPostData) . "\r\n";
 			$postStr .= $postContentLength;
 		    fputs($fp, $postContentLength);
-			
+
 			$postClose = "Connection: close\r\n\r\n";
 			$postStr .= $postClose;
 		    fputs($fp, $postClose);
@@ -406,7 +415,7 @@
 			fputs($fp, $this->httpPostData);
 
 			new mb_notice("connector.http.postData: ".$this->httpPostData);
-			
+
 		    $xmlstr = false;
 		    //@TODO remove possibly infinite loop
 			while (!feof($fp)) {
@@ -421,7 +430,7 @@
 			}
 		    fclose($fp);
 //		    new mb_notice("connector.http.response: ".$buf);
-		    return $buf;			
+		    return $buf;
 		}
 	}
 
@@ -430,7 +439,7 @@
 		$fp = fsockopen (CONNECTION_PROXY, CONNECTION_PORT, $errno, $errstr, 30);
 		if (!$fp) {
 			echo "$errstr ($errno)<br />\n";
-		} 
+		}
 		else {
 			fputs ($fp, "GET ".$url." HTTP/1.0\r\n\r\n");
 			while (!feof($fp)) {

Modified: trunk/mapbender/http/classes/class_kml_ows.php
===================================================================
--- trunk/mapbender/http/classes/class_kml_ows.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/classes/class_kml_ows.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -1,7 +1,7 @@
 <?php
 # $Id$
 # http://www.mapbender.org/index.php/class_wmc.php
-# Copyright (C) 2002 CCGIS 
+# Copyright (C) 2002 CCGIS
 #
 # 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
@@ -28,7 +28,7 @@
 
 /**
  * Allows parsing a KML file, extracting the placemarks.
- * 
+ *
  * @package KML
  */
 class KML {
@@ -41,21 +41,21 @@
 
 	/**
 	 * The constructor function, currently empty.
-	 */				
+	 */
 	public function __construct() {
-	} 
+	}
 
 	public function toSingleLineStringKml() {
 		//KML 2.2 output
 		$doc = new DOMDocument("1.0", CHARSET);
 		$doc->preserveWhiteSpace = false;
-	
+
 		// attach kml and Document tag
 		$e_kml = $doc->createElementNS("http://earth.google.com/kml/2.2", "kml");
 		$e_document = $doc->createElement("Document");
 		$e_kml->appendChild($e_document);
 		$doc->appendChild($e_kml);
-	
+
 		// attach placemarks
 		$e = new mb_notice("to string: #placemarks: " . count($this->placemarkArray));
 
@@ -66,7 +66,7 @@
 		$lineStyleNode->appendChild($lineStyleColorNode);
 		$lineStyleNode->appendChild($lineStyleWidthNode);
 		$e_document->appendChild($lineStyleNode);
-		
+
 		//
 		// line segments first
 		//
@@ -84,7 +84,7 @@
 							$coordinates .= " ";
 						}
 						$coordinates .= $coordinatesArray[$j]["x"] . "," . $coordinatesArray[$j]["y"] . "," . $coordinatesArray[$j]["z"];
-						
+
 					}
 					break;
 			}
@@ -100,8 +100,8 @@
 		$e_pl_style = $doc->createElement("styleUrl", "#linestyleExample");
 		$e_placemark->appendChild($e_pl_style);
 		$e_document->appendChild($e_placemark);
-		
-/*		
+
+/*
 		//
 		// now pois
 		//
@@ -111,7 +111,7 @@
 			$currentPlacemark = $this->placemarkArray[$i];
 
 			$e = new mb_notice("now: " . $i . " of " . (count($this->placemarkArray)-1) . " (is a " . get_class($currentPlacemark) . ")");
-			
+
 			$pl_instructions = $currentPlacemark->getProperty("instruction");
 			$pl_name_array = array();
 			$pl_name = false;
@@ -152,31 +152,31 @@
 */
 		return $doc->saveXML();
 	}
-	
+
 	/**
 	 * @return string the KML document.
 	 */
 	public function __toString() {
-		
-	
+
+
 		if (!$this->kml) {
 			//KML 2.2 output
 			$doc = new DOMDocument("1.0", CHARSET);
 			$doc->preserveWhiteSpace = false;
-	
+
 			// attach kml and Document tag
 			$e_kml = $doc->createElementNS("http://earth.google.com/kml/2.2", "kml");
 			$e_document = $doc->createElement("Document");
 			$e_kml->appendChild($e_document);
 			$doc->appendChild($e_kml);
-	
+
 			// attach placemarks
 			$e = new mb_notice("to string: #placemarks: " . count($this->placemarkArray));
 			for ($i = 0; $i < count($this->placemarkArray); $i++) {
 				$currentPlacemark = $this->placemarkArray[$i];
 
 				$e = new mb_notice("now: " . $i . " of " . (count($this->placemarkArray)-1) . " (is a " . get_class($currentPlacemark) . ")");
-				
+
 				$pl_instructions = $currentPlacemark->getProperty("instruction");
 				$pl_name_array = array();
 				$pl_name = false;
@@ -197,7 +197,7 @@
 						$e_coordinates = $doc->createElement("coordinates", $coordinates);
 						$e_geometry->appendChild($e_coordinates);
 						break;
-					
+
 /* TODO:Polygons
 					case "KMLPolygon" :
 						$e_geometry = $doc->createElement("Polygon");
@@ -205,19 +205,19 @@
 						$e_outer_lr = $doc->createElement("LinearRing");
 						$outer_coordinates = ""; // TODO: get coords from placemark
 						$e_outer_coordinates = $doc->createElement("Coordinates", $outer_coordinates);
-						
+
 						$e_outer_lr->appendChild($e_outer_coordinates);
 						$e_outer->appendChild($e_outer_lr);
-						
+
 						for ($j = 0; $j < $currentPlacemark; $j++) {
-							
+
 						}
-						
+
 						$e_geometry->appendChild($e_coordinates);
 					outerBoundaryIs"}->{"LinearRing"}->{"coordinates
-					
+
 						break;
-*/					
+*/
 					case "KMLLine" :
 						if (count($pl_name_array) > 2) {
 							$pl_description = $pl_name_array[1];
@@ -230,13 +230,13 @@
 								$coordinates .= " ";
 							}
 							$coordinates .= $coordinatesArray[$j]["x"] . "," . $coordinatesArray[$j]["y"] . "," . $coordinatesArray[$j]["z"];
-							
+
 						}
 						$e_coordinates = $doc->createElement("coordinates", $coordinates);
 						$e_geometry->appendChild($e_coordinates);
 						break;
 
-/*	TODO: Multigeometries				
+/*	TODO: Multigeometries
 					case "KMLMultiGeometry" :
 						break;
 */
@@ -260,18 +260,18 @@
 		}
 		return $this->kml;
 	}
-	
+
 	/**
 	 * @return string the ID of this KML.
 	 */
 	public function getId () {
 		return $this->id;
 	}
-	
+
 	/**
-	 * parses an incoming KML, creates the object, 
+	 * parses an incoming KML, creates the object,
 	 * stores the kml in the object and in the database.
-	 * 
+	 *
 	 * @param  string  a KML document.
 	 * @return boolean true if the parsing succeded, else false.
 	 */
@@ -284,11 +284,11 @@
 
 		$parser = new KmlOwsParser();
 		$parser->parseKML($kml, $this->id);
-		$this->placemarkArray = $parser->placemarkArray; 
-
+		$this->placemarkArray = $parser->placemarkArray;
+		$this->featureCollectionMD = $parser->featureCollectionMD;
 		return true;
 	}
-	
+
 	public function transform($targetEpsg){
 	    $numberOfPlacemarks = count($this->placemarkArray);
 		if ($numberOfPlacemarks > 0) {
@@ -302,9 +302,9 @@
 		return true;
 	}
 	/**
-	 * parses an incoming GeoJSON, creates the object, 
+	 * parses an incoming GeoJSON, creates the object,
 	 * stores the kml in the object and in the database.
-	 * 
+	 *
 	 * @param string a geoJSON.
 	 * @return boolean true if the parsing succeded, else false.
 	 */
@@ -318,28 +318,48 @@
 		$parser = new KmlOwsParser();
 		$parser->parseGeoJSON($geoJSON, $this->id);
 		$e = new mb_notice("parsing finished...#placemarks: " . count($this->placemarkArray) . " (" . count($parser->placemarkArray) . ")");
-		$this->placemarkArray = $parser->placemarkArray; 
+		$this->placemarkArray = $parser->placemarkArray;
 
 //		new mb_exception(print_r($this, true));
-		
+
 //		$this->kml = $this->__toString();
 
 //		$this->updateInDb($this->kml, $this->id);
 		return true;
 	}
-	
+
 	/**
 	 * @return string the geoJSON representation of the KML.
 	 */
-	public function toGeoJSON() {
-	    $str = "";
+	public function toGeoJSON($str) {
+		// var_dump($str);die;
+	 //    $str = "{";
 		$numberOfPlacemarks = count($this->placemarkArray);
+		// if (sizeof($this->featureCollectionMD) > 0) {
+		// 	end($this->featureCollectionMD);
+		// 	$lastKey = key($this->featureCollectionMD);
+
+		// 	$str .= "\"@context\": {  ";
+		// 	foreach ($this->featureCollectionMD as $key => $value) {
+		// 		// var_dump($str);var_dump($key);var_dump($value);
+		// 		// if ($key == end($this->featureCollectionMD)){
+		// 		if ( $key === $lastKey ){
+
+		// 			$str.= "\"".$key."\": \"".$value."\" },";
+
+		// 		}else{
+
+		// 			$str.= "\"".$key."\": \"".$value."\",";
+		// 		}
+		// 	}
+
+		// }
 		if ($numberOfPlacemarks > 0) {
-			$str .= "{\"type\": \"FeatureCollection\", \"features\": [";
+			$str .= "\"type\": \"FeatureCollection\", \"features\": [";
 			for ($i=0; $i < $numberOfPlacemarks; $i++) {
 				if ($i > 0) {
 					$str .= ",";
-				}	
+				}
 				$str .= $this->placemarkArray[$i]->toGeoJSON();
 			}
 			$str .= "]}";
@@ -350,6 +370,33 @@
 		return $str;
 	}
 
+	public function createGeoJSON(){
+		// var_dump($this->placemarkArray);die;
+   		$str = "{";
+	    if (sizeof($this->featureCollectionMD) > 0) {
+			end($this->featureCollectionMD);
+			$lastKey = key($this->featureCollectionMD);
+
+			$str .= "\"@context\": {  ";
+			foreach ($this->featureCollectionMD as $key => $value) {
+				// var_dump($str);var_dump($key);var_dump($value);
+				// if ($key == end($this->featureCollectionMD)){
+				if ( $key === $lastKey ){
+
+					$str.= "\"".$key."\": \"".$value."\" },";
+
+				}else{
+
+					$str.= "\"".$key."\": \"".$value."\",";
+				}
+			}
+
+		}
+		// var_dump($str);die;
+		$completeString = $this->toGeoJSON($str);
+		return $completeString;
+		// var_dump($completeString);die;
+	}
 	private function updateInDb($kmlDoc, $kmlId) {
 		$sql = "UPDATE gui_kml SET kml_doc = $1 WHERE kml_id = $2";
 		$v = array($kmlDoc, $kmlId);
@@ -363,13 +410,13 @@
 
 	public function updateKml ($kmlId, $placemarkId, $geoJSON) {
 		$kmlFromDb = $this->getKmlDocumentFromDB($kmlId);
-		 
+
 		if ($kmlFromDb !== NULL) {
 			// load the KML from the database in the DOM object
 			$kmlDoc_DOM = new DOMDocument("1.0");
 			$kmlDoc_DOM->encoding = CHARSET;
 			$kmlDoc_DOM->preserveWhiteSpace = false;
-			$kmlDoc_DOM->loadXML($kmlFromDb); 
+			$kmlDoc_DOM->loadXML($kmlFromDb);
 
 			//load the geoJSON
 			$json = new Mapbender_JSON();
@@ -377,7 +424,7 @@
 
 			// construct an array that holds all metadata of the placemark
 			$metadataObj = $geoObj->properties;
-			
+
 			// construct an array that holds all geometries of the placemark
 			$geometryObj = $geoObj->geometry;
 			$geometryType = $geometryObj->type;
@@ -395,7 +442,7 @@
 			//
 			// apply the changes
 			//
-			
+
 			$currentPlacemarkArray = $kmlDoc_DOM->getElementsByTagName("Placemark");
 			$currentPlacemark = $currentPlacemarkArray->item($placemarkId);
 
@@ -435,17 +482,17 @@
 	// ------------------------------- private -----------------------------------------------
 	//
 	//
-		
+
 	/**
 	 * Store this KML in the database, and sets the ID.
-	 * 
+	 *
 	 * @return boolean true, if the KML could be stored in the database; else false.
 	 */
 	private function storeInDb () {
 		if (Mapbender::session()->get("mb_user_id") && Mapbender::session()->get("mb_user_gui")) {
 			$con = db_connect(DBSERVER,OWNER,PW);
 			db_select_db(DB,$con);
-	
+
 			$sql  = "INSERT INTO gui_kml ";
 			$sql .= "(fkey_mb_user_id, fkey_gui_id, kml_doc, kml_name, kml_description, kml_timestamp) ";
 			$sql .= "VALUES ";
@@ -457,7 +504,7 @@
 				$e = new mb_exception("class_kml.php: storeInDb: failed to store KML in database: " . db_error());
 				return false;
 			}
-	
+
 			$this->id = db_insert_id($con, "gui_kml", "kml_id");
 			return true;
 		}
@@ -476,7 +523,7 @@
 		db_select_db(DB,$con);
 		//get KML from database (check if user is allowed to access)
 
-# for now, do not restrict access 
+# for now, do not restrict access
 #		$sql = "SELECT kml_doc FROM gui_kml WHERE kml_id = $1 AND fkey_mb_user_id = $2 AND fkey_gui_id = $3 LIMIT 1";
 #		$v = array($kmlId, Mapbender::session()->get("mb_user_id"), Mapbender::session()->get("mb_user_gui"));
 #		$t = array("i", "i", "s");
@@ -501,7 +548,7 @@
 	 * @return string the tag name without its namespace.
 	 */
 	private function sepNameSpace($s){
-		$c = mb_strpos($s, ":"); 
+		$c = mb_strpos($s, ":");
 		if ($c > 0) {
 			$s = mb_substr($s, $c+1);
 		}
@@ -509,7 +556,7 @@
 	}
 
 	private function updateGeometries($currentPlacemark, $geometryArray) {
-		$cnt = 0; 
+		$cnt = 0;
 		$childNodes = $currentPlacemark->childNodes;
 
 		foreach ($childNodes as $childNode) {
@@ -527,13 +574,13 @@
 		}
 		return true;
 	}
-	
+
 	private function updateGeometry ($currentNode, $geometry) {
 		$json = new Mapbender_JSON();
 		$currentNode_SimpleXML = simplexml_import_dom($currentNode);
 
 		$currentTypeXml = mb_strtoupper($currentNode->nodeName);
-		$currentTypeGeoJson = mb_strtoupper($geometry->type);  
+		$currentTypeGeoJson = mb_strtoupper($geometry->type);
 
 		if ($currentTypeGeoJson != $currentTypeXml) {
 			$e = new mb_exception("class_kml: geometry type mismatch: geoJSON: " . $currentTypeGeoJson . "; XML: " . $currentTypeXml);
@@ -582,7 +629,7 @@
 
 	private function updateMetadata($currentPlacemark, $metadataObj) {
 		$metadataExistsAndUpdateSucceeded = true;
-		
+
 		$currentPlacemark_SimpleXML = simplexml_import_dom($currentPlacemark);
 		$extendedDataNode = $currentPlacemark_SimpleXML->{"ExtendedData"};
 		if ($extendedDataNode) {
@@ -592,12 +639,12 @@
 			$simpleDataNodes = $extendedDataNode->{"SchemaData"}->{"SimpleData"};
 			if ($simpleDataNodes) {
 				foreach ($simpleDataNodes as $simpleDataNode) {
-					$tmp = dom_import_simplexml($simpleDataNode);					
+					$tmp = dom_import_simplexml($simpleDataNode);
 					$name = $tmp->getAttribute("name");
 					// if there is a metadata entry, update it
 					if (isset($metadataObj->$name)) {
 						$tmp->nodeValue = $metadataObj->$name;
-					}										
+					}
 				}
 
 				$metadataExistsAndUpdateSucceeded = true;
@@ -612,7 +659,7 @@
 					// if there is a metadata entry, update it
 					if (isset($metadataObj->$name)) {
 						$tmp->nodeValue = $metadataObj->$name;
-					}										
+					}
 				}
 				$metadataExistsAndUpdateSucceeded = true;
 			}
@@ -624,15 +671,15 @@
 	 * The KML document.
 	 */
 	private $kml;
-	
+
 	/**
 	 * The ID of this KML in the database.
 	 */
 	private $id;
-	
+
 	/**
 	 * An array of {@link KMLPlacemark}
 	 */
 	private $placemarkArray = array();
-} 
+}
 ?>

Modified: trunk/mapbender/http/classes/class_kml_parser_ows.php
===================================================================
--- trunk/mapbender/http/classes/class_kml_parser_ows.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/classes/class_kml_parser_ows.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -1,7 +1,7 @@
 <?php
 # $Id$
 # http://www.mapbender.org/index.php/class_wmc.php
-# Copyright (C) 2002 CCGIS 
+# Copyright (C) 2002 CCGIS
 #
 # 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
@@ -32,20 +32,21 @@
  */
  class KmlOwsParser {
 	var $placemarkArray = array();
-	
+	var $featureCollectionMD = array();
+
 	public function __construct() {
 	}
-	
+
 	public function parseGeoJSON ($geoJSON, $kmlId) {
-		
+
 //		$e = new mb_notice("GEOJSON: " . $geoJSON);
 		$json = new Mapbender_JSON();
 		$geometryFromGeoJSON = $json->decode($geoJSON);
 		$id = 0;
-		
+
 		if (gettype($geometryFromGeoJSON) == "object" && $geometryFromGeoJSON->type == "FeatureCollection") {
 			if ($geometryFromGeoJSON->crs->type == "EPSG" && $geometryFromGeoJSON->crs->properties->code) {
-				$epsg = $geometryFromGeoJSON->crs->properties->code;	
+				$epsg = $geometryFromGeoJSON->crs->properties->code;
 			}
 			// create Placemarks
 			for ($i = 0; $i < count($geometryFromGeoJSON->features); $i++) {
@@ -53,14 +54,14 @@
 				$feature = $geometryFromGeoJSON->features[$i];
 				if (gettype($feature) == "object" && $feature->type == "Feature") {
 					if ($feature->geometry->crs->type == "EPSG") {
-						$epsg = $feature->geometry->crs->properties->code;	
+						$epsg = $feature->geometry->crs->properties->code;
 					}
 					if (!$epsg) {
 						$e = new mb_notice("EPSG is not set! Aborting...(" . $epsg . ")");
+					$currentGeometry = false;
 					}
 					$geometry = $feature->geometry;
-					
-					$currentGeometry = false;
+
 					//TODO: missing Polygon and MultiGeometry
 					switch ($geometry->type) {
 						case "LineString" :
@@ -78,12 +79,12 @@
 							$currentGeometry = new KMLPoint($coordinateList, $epsg);
 							break;
 					}
-					
+
 					if ($currentGeometry) {
 						$currentPlacemark = new KMLPlacemark($currentGeometry);
 
 						if (gettype($feature->properties) == "object") {
-							
+
 							foreach ($feature->properties as $key => $value) {
 								$currentPlacemark->setProperty($key, $value);
 							}
@@ -102,52 +103,53 @@
 		}
 		return true;
 	}
-		
+
 	public function parseKML ($kml, $kmlId) {
 		$doc = new DOMDocument("1.0");
 		$doc->preserveWhiteSpace = false;
 		$doc->loadXML($kml);
 		$xpath = new DOMXPath($doc);
 		$xpath->registerNamespace("kml","http://earth.google.com/kml/2.2");
+		$xpath->registerNamespace("http://www.opengis.net/kml/2.2");
 
 		$styles =array();
 		$styleNodes = $xpath->query("/kml:kml/kml:Document/kml:Style");
-		
+
 		//$e = new mb_exception("found this many styles:". $styleNodes->length);
 		foreach($styleNodes as $styleNode){
-		    $hrefNodes = $styleNode->getElementsByTagName("href");	
+		    $hrefNodes = $styleNode->getElementsByTagName("href");
 		    if($hrefNodes->length > 0){
 			    $href = $hrefNodes->item(0)->nodeValue;
 			    $styles[$styleNode->getAttribute("id")] = array(
 			        "href" => $href
-			    );	
-		    }	        
+			    );
+		    }
 		}
-		
+
 		$styleMapNodes = $xpath->query("/kml:kml/kml:Document/kml:StyleMap");
 		//$e = new mb_exception($styleMapNodes->length);
 		foreach($styleMapNodes as $styleMapNode){
-		    
+
 		    foreach($styleMapNode->children as $child){
 		        $keyNodes = $child->findElementsByTagName("key");
 		        if($keyNodes->length > 0){
 		            if($keyNodes->item(0)->nodeValue == "normal"){
-		                
-		                
+
+
     		            $styleNodes = $child->findElementsByTagName("Style");
     		            if($styleNodes->length > 0){
-        		            $hrefNodes = $styleNodes->item(0)->getElementsByTagName("href");	
+        		            $hrefNodes = $styleNodes->item(0)->getElementsByTagName("href");
         		            if($hrefNodes->length > 0){
         			            $href = $hrefNodes->item(0)->nodeValue;
         			            $styles[$styleMapNode->getAttribute("id")] = array(
         			        	"href" => $href
         			            );
-        			            continue;	
+        			            continue;
         		            }
     		            }
-    		            
-		                
-		                
+
+
+
 		                $styleUrlNodes = $child->findElementsByTagName("styleUrl");
 		                if($styleUrlNodes->length > 0){
 		                    $id = $styleUrlNodes->item(0)->nodeValue;
@@ -155,11 +157,11 @@
 					            $id = substr($id,1);
 					            $styles[$styleMapNode->getAttribute("id")] = array(
 					                "href" => $styles[$id]["href"]
-					            ); 
+					            );
 					        }else{
 					            $e = new mb_exception("External style references not supported in KML parser");
 					        }
-		                    
+
 		                }
 		            }
 		        }
@@ -168,34 +170,30 @@
 				"href" => $href
 			);
 		}
-		
 		/*
 		 * Get geometry information only, store it in placemarkArray
 		 */
 		$placemarkTagArray = $doc->getElementsByTagName("Placemark");
-		
+
 		if (count($placemarkTagArray) > 0) {
 			$id = 0;
-			
+
 			foreach ($placemarkTagArray as $node) {
-	
 				$geometryArray = $this->getGeometryArrayFromPlacemarkOrMultigeometryNode($node);
 				$metadataArray = $this->getMetadataFromPlacemarkNode($node);
-				
 				/*
 				 * For a placemark, the geometryArray should only contain 1 geometry!
 				 */
 				for ($i=0; $i < count($geometryArray); $i++) {
 				    $currentPlacemark = new KMLPlacemark($geometryArray[$i]);
-				    
-				    foreach ($metadataArray as $key => $value) {
-						$currentPlacemark->setProperty($key, $value);
-					}
-					
+
 					$currentPlacemark->setProperty("Mapbender:kml", true);
 					$currentPlacemark->setProperty("Mapbender:name", "unknown");
 					$currentPlacemark->setProperty("Mapbender:id", $kmlId);
 					$currentPlacemark->setProperty("Mapbender:placemarkId", $id);
+				    foreach ($metadataArray as $key => $value) {
+						$currentPlacemark->setProperty($key, $value);
+					}
 
 					// add description and name:
 					$namesNode = $node->getElementsByTagName('name');
@@ -206,8 +204,9 @@
 					if($descriptionsNode->length > 0){
 						$description = trim($descriptionsNode->item(0)->nodeValue);
 					}
-					$currentPlacemark->setProperty("name", $name);
-					$currentPlacemark->setProperty("description", $description);
+					//TODO: dont add the properties twice!
+					// $currentPlacemark->setProperty("name", $name);
+					// $currentPlacemark->setProperty("description", $description);
 
 					//get style information for KML point objects
 					if(get_class($geometryArray[$i]) == "KMLPoint") {
@@ -215,11 +214,11 @@
     					$styleNodes = $node->getElementsByTagName('Style');
     					if($styleNodes->length > 0) {
     				        $styleNode = $styleNodes->item(0);
-    				        $hrefNodes = $styleNode->getElementsByTagName("href");	
+    				        $hrefNodes = $styleNode->getElementsByTagName("href");
             			    if($hrefNodes->length > 0){
             				    $href = $hrefNodes->item(0)->nodeValue;
-            				    $currentPlacemark->setProperty("Mapbender:icon",$href);	
-            			    }	        
+            				    $currentPlacemark->setProperty("Mapbender:icon",$href);
+            			    }
     					}else{
     					    $styleUrlNodes = $node->getElementsByTagName('styleUrl');
     					    if($styleUrlNodes->length > 0) {
@@ -234,21 +233,47 @@
     					        }
     					        $e = new mb_notice("Looking up style: $id");
     				             $currentPlacemark->setProperty("Mapbender:icon",$styles[$id]["href"]);
-    					        
+
     					    }
     					}
 					}
-					
-					
+
 					array_push($this->placemarkArray, $currentPlacemark);
 				}
-				$id ++;		    
+				$id ++;
 			}
 		}
 		else {
 			$e = new mb_exception("class_kml.php: KMLOWSParser: No placemarks found in KML.");
 			return false;
 		}
+
+
+
+		/**
+		 * add metadata for the feature-collection
+		 *
+		 */
+		$extendedData = $xpath->query('//*[local-name() = "kml"]/*[local-name() = "Document"]/*[local-name() = "ExtendedData"]');
+		if ($extendedData->length > 0) { // check for metadata
+
+    		foreach ($extendedData as $metaData) {
+
+    			$data = $metaData->getElementsByTagName('Data');
+    			foreach ($data as $metadataValue) {
+
+					$test = $metadataValue->nodeValue;
+
+					foreach($metadataValue->attributes as $attribute_name => $attribute_node){
+  						// * @var  DOMNode    $attribute_node
+  						$this->featureCollectionMD[$attribute_node->nodeValue] = $metadataValue->nodeValue;
+					}
+				}
+
+			}
+
+		}
+
 		return true;
 	}
 
@@ -257,15 +282,15 @@
 	 */
 	private function getMetadataFromPlacemarkNode ($node) {
 	    $children = $node->childNodes;
-	    
+
 	    $metadataArray = array();
-	    
+
 		// search "ExtendedData" tag
 		foreach ($children as $child) {
-			if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "EXTENDEDDATA") {  
+			if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "EXTENDEDDATA") {
 				$extendedDataNode = $child;
-				$extDataChildren = $extendedDataNode->childNodes; 
-				
+				$extDataChildren = $extendedDataNode->childNodes;
+
 				// search "Data" or "SchemaData" tag
 				foreach ($extDataChildren as $extDataChild) {
 					if (mb_strtoupper($this->sepNameSpace($extDataChild->nodeName)) == "SCHEMADATA") {
@@ -287,17 +312,17 @@
 				}
 			}
 			if(mb_strtoupper($this->sepNameSpace($child->nodeName)) == "STYLE"){
-			$hrefNodes = $child->getElementsByTagName("href");	
+			$hrefNodes = $child->getElementsByTagName("href");
 			if($hrefNodes->length > 0){
 				$href = $hrefNodes->item(0)->nodeValue;
-				$metadataArray["iconurl"] = $href;	
-			}	
-					
+				$metadataArray["iconurl"] = $href;
 			}
+
+			}
 		}
-		return $metadataArray;		
+		return $metadataArray;
 	}
-	
+
 	/**
 	 * Given a "Point" node, this function returns the geometry (KMLPoint)
 	 * from within the node.
@@ -307,7 +332,7 @@
 		$geomString = $coordinatesNode->nodeValue;
 		return new KMLPoint($geomString, 4326);
 	}
-	
+
 	/**
 	 * Given a "LineString" node, this function returns the geometry (KMLLine)
 	 * from within the node.
@@ -317,7 +342,7 @@
 		$geomString = $coordinatesNode->nodeValue;
 		return new KMLLine($geomString, 4326);
 	}
-	
+
 	/**
 	 * Given a "Polygon" node, this function returns the geometry (KMLPolygon)
 	 * from within the node.
@@ -326,21 +351,21 @@
 		$polygon = null;
 
 	    $children = $node->childNodes;
-	    
+
 		// create new KMLPolygon
 		foreach ($children as $child) {
-			if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "EXTERIOR" || 
+			if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "EXTERIOR" ||
 				mb_strtoupper($this->sepNameSpace($child->nodeName)) == "OUTERBOUNDARYIS") {
 				// create a new Linear Ring
 				$outerBoundary = $this->getGeometryFromLinearRingNode($child);
 				$polygon = new KMLPolygon($outerBoundary);
 			}
 		}
-		
+
 		if ($polygon !== null) {
 			// append inner boundaries to KMLPolygon
 			foreach ($children as $child) {
-				if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "INTERIOR" || 
+				if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "INTERIOR" ||
 					mb_strtoupper($this->sepNameSpace($child->nodeName)) == "INNERBOUNDARYIS") {
 					// create a new Linear Ring
 					$innerBoundary = $this->getGeometryFromLinearRingNode($child);
@@ -350,9 +375,9 @@
 		}
 		return $polygon;
 	}
-	
+
 	/**
-	 * Given a "OuterBoundaryIs" or "InnerBoundaryIs" node, this function 
+	 * Given a "OuterBoundaryIs" or "InnerBoundaryIs" node, this function
 	 * returns the geometry (KMLLinearRing) within the child node named "linearring"
 	 */
 	private function getGeometryFromLinearRingNode ($node) {
@@ -366,14 +391,14 @@
 		}
 		return null;
 	}
-	
+
 	/**
 	 * Checks if the child nodes of a given KML node contains any geometries and
 	 * returns an array of geometries (KMLPoint, KMLPolygon, KMLLinestring and KMLMultigeometry)
 	 */
 	private function getGeometryArrayFromPlacemarkOrMultigeometryNode ($node) {
 	    $geometryArray = array();
-	    
+
 	    $children = $node->childNodes;
 		foreach($children as $child) {
 		    if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "POINT") {
@@ -388,9 +413,9 @@
 			elseif (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "MULTIGEOMETRY") {
 				$geometryArray = $this->getGeometryArrayFromPlacemarkOrMultigeometryNode($child);
 				$multigeometry = new KMLMultiGeometry();
-				
+
 				for ($i=0; $i < count($geometryArray); $i++) {
-					$multigeometry->append($geometryArray[$i]);	
+					$multigeometry->append($geometryArray[$i]);
 				}
 				array_push($geometryArray, $multigeometry);
 			}
@@ -405,8 +430,8 @@
 	private function getCoordinatesNode ($node) {
 	    $children = $node->childNodes;
 		foreach($children as $child) {
-			if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "POSLIST" || 
-				mb_strtoupper($this->sepNameSpace($child->nodeName)) == "POS" || 
+			if (mb_strtoupper($this->sepNameSpace($child->nodeName)) == "POSLIST" ||
+				mb_strtoupper($this->sepNameSpace($child->nodeName)) == "POS" ||
 				mb_strtoupper($this->sepNameSpace($child->nodeName)) == "COORDINATES") {
 				return $child;
 			}
@@ -415,13 +440,13 @@
 	}
 
 	private function sepNameSpace($s){
-		$c = mb_strpos($s,":"); 
+		$c = mb_strpos($s,":");
 		if($c>0){
 			return mb_substr($s,$c+1);
 		}
 		else{
 			return $s;
-		}		
+		}
 	}
 }
 ?>

Modified: trunk/mapbender/http/extensions/togeojson.js
===================================================================
--- trunk/mapbender/http/extensions/togeojson.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/extensions/togeojson.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -211,6 +211,7 @@
             return gj;
         },
         gpx: function(doc, o) {
+            // console.log('test');
             var i,
                 tracks = get(doc, 'trk'),
                 routes = get(doc, 'rte'),

Modified: trunk/mapbender/http/extensions/togpx.js
===================================================================
--- trunk/mapbender/http/extensions/togpx.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/extensions/togpx.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -2,6 +2,7 @@
 var JXON = require("jxon");
 
 function togpx( geojson, options ) {
+  console.log(geojson);
   options = (function (defaults, options) {
     for (var k in defaults) {
       if (options.hasOwnProperty(k))
@@ -10,7 +11,6 @@
     return defaults;
   })({
     creator: "togpx",
-    metadata: undefined,
     featureTitle: get_feature_title,
     featureDescription: get_feature_description,
     featureLink: undefined
@@ -28,6 +28,8 @@
     }
     if (props.name)
       return props.name;
+    if (props.title)
+      return props.title;
     if (props.ref)
       return props.ref;
     if (props.id)
@@ -65,7 +67,7 @@
     gpx.gpx["@creator"] = options.creator;
   if (options.metadata)
     gpx.gpx["metadata"] = options.metadata;
-  
+
   var features;
   if (geojson.type === "FeatureCollection")
     features = geojson.features;
@@ -264,7 +266,7 @@
     if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) {
       oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 */
     } else if (oParentObj.constructor === Date) {
-      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));    
+      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));
     }
 
     for (var sName in oParentObj) {
@@ -296,10 +298,10 @@
 
   this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
     var _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
-    return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3);    
+    return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3);
   };
 
-  this.unbuild = function (oObjTree) {    
+  this.unbuild = function (oObjTree) {
     var oNewDoc = document.implementation.createDocument("", "", null);
     loadObjTree(oNewDoc, oNewDoc, oObjTree);
     return oNewDoc;
@@ -316,4 +318,4 @@
 },{}]},{},[1])
 (1)
 });
-;
\ No newline at end of file
+;

Modified: trunk/mapbender/http/extensions/tokml.js
===================================================================
--- trunk/mapbender/http/extensions/tokml.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/extensions/tokml.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -4,7 +4,7 @@
     encode = strxml.encode;
 
 module.exports = function tokml(geojson, options) {
-
+    console.log(geojson);
     options = options || {
         documentName: undefined,
         documentDescription: undefined,
@@ -18,6 +18,7 @@
             tag('Document',
                 documentName(options) +
                 documentDescription(options) +
+                documentMetadata(geojson,options) + // add metadata to feautureCollections
                 root(geojson, options)
                ), [['xmlns', 'http://www.opengis.net/kml/2.2']]);
 };
@@ -64,6 +65,17 @@
     return (options.documentName !== undefined) ? tag('name', options.documentName) : '';
 }
 
+function documentMetadata(geojson,options) {
+
+    var metadata = {};
+    for(key in geojson['@context']){
+
+        metadata[key]= geojson['@context'][key];
+
+    }
+    extendeddata(metadata);
+    return extendeddata(metadata);
+}
 function documentDescription(options) {
     return (options.documentDescription !== undefined) ? tag('description', options.documentDescription) : '';
 }
@@ -139,6 +151,7 @@
 
 // ## Data
 function extendeddata(_) {
+
     return tag('ExtendedData', pairs(_).map(data).join(''));
 }
 
@@ -217,6 +230,15 @@
 
 /**
  * @param {string} el element name
+ * @param {array} attributes array of pairs
+ * @returns {string}
+ */
+function tagOpen(el, attributes) {
+    return '<' + el + attr(attributes) + '>';
+}
+
+/**
+ * @param {string} el element name
  * @param {string} contents innerXML
  * @param {array} attributes array of pairs
  * @returns {string}
@@ -238,4 +260,4 @@
 
 },{}]},{},[1])
 (1)
-});
\ No newline at end of file
+});

Modified: trunk/mapbender/http/javascripts/mod_savewmc.js
===================================================================
--- trunk/mapbender/http/javascripts/mod_savewmc.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/javascripts/mod_savewmc.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -219,7 +219,6 @@
 
 		// title
 		$("#" + options.id + "_saveWMCForm").dialog('option', 'title', translatedI18nObj.title);
-
 		//
 		// form
 		//
@@ -440,7 +439,6 @@
 	});
 
 	Mapbender.events.init.register(function () {
-
 		var t = translatedI18nObj;
 		var savewmcHtml = '<div id="' + options.id + '_saveWMCForm" ' +
 			'title="' + translatedI18nObj.title + '">' +
@@ -466,6 +464,7 @@
 			},
 			buttons: getButtons()
 		});
+		// set uuid
 	});
 
 //	Mapbender.events.localize.register(function () {

Modified: trunk/mapbender/http/javascripts/mod_savewmc.php
===================================================================
--- trunk/mapbender/http/javascripts/mod_savewmc.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/javascripts/mod_savewmc.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -84,10 +84,7 @@
 $labelCategories = $translatedI18nObj["labelCategories"];
 
 echo <<<HTML
-//TODO: add input for uuid,title already there. created and updated need no input.just save it to the database...
 
-var wmc_uuid = UUID.genV4().toString();
-
 var wmcSaveFormHtml = '<form><fieldset>' +
 	'<label for="{$e_id}_wmctype">{$labelNewOrOverwrite}</label>' +
 	'<select class="ui-corner-all" id="{$e_id}_wmctype">' +
@@ -99,8 +96,6 @@
 	'<label for="{$e_id}_wmckeywords">{$labelKeywords}</label>' +
 	'<input id="{$e_id}_wmckeywords" type="text" class="text ui-widget-content ui-corner-all" />' +
 	'<input id="{$e_id}_wmc_id" type="hidden" />' +
-	'<input id="{$e_id}_wmc_id" type="hidden" />' +
-	'<input id="{$e_id}_wmc_uuid" value={wmc_uuid} />' +
 	'</fieldset><fieldset id="{$e_id}_isoTopic_cat"><legend>{$labelCategories}' +
 	'</legend>' +
 	'{$saveWmcCategoryString}' +

Modified: trunk/mapbender/http/php/kmlToGeoJSON.php
===================================================================
--- trunk/mapbender/http/php/kmlToGeoJSON.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/php/kmlToGeoJSON.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -1,6 +1,6 @@
 <?php
 # http://www.mapbender.org/index.php/Administration
-# Copyright (C) 2002 CCGIS 
+# Copyright (C) 2002 CCGIS
 #
 # 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
@@ -23,32 +23,38 @@
 
 //FIXME: what about projections?
 //header("Content-Type: text/x-json");
-
 if(isset($_REQUEST["url"])){
-	$url = $_REQUEST["url"];
+    $url = $_REQUEST["url"];
 }else{
-	echo("{}");
-	exit;
+    echo("{}");
+    exit;
 }
-
-
 $kml = new KML();
 $con = new connector();
-$kmlString = $con->load($url);
+$content = $con->load($url);
+
 try {
-	
-	if($kml->parseKml($kmlString)){
-	    $kml->transform($_REQUEST["targetEPSG"]);
-		$geojson  =  $kml->toGeoJSON();
-		echo $geojson;
-	}else{
-		echo("{}");
-	}
-	
-	
+    if(preg_match('/.kml$/', $url)) {
+        header("Content-Type: text/plain");
+        if($kml->parseKml($content)){
+            $geojson  =  $kml->createGeoJSON();
+            echo $geojson;
+        }else{
+            echo("{}");
+        }
+    }
+    if(preg_match('/.(json|geojson)$/', $url)) {
+        header("Content-Type: text/plain");
+        echo $content;
+    }
+    if(preg_match('/.(xml|gpx)$/', $url)) {
+        header("Content-Type: text/plain");
+        echo $content;
+    }
+
 } catch (Exception $e) {
-	echo($e);
-	die;
+    echo($e);
+    die;
 }
 
 ?>

Modified: trunk/mapbender/http/php/mb_metadata_uploadLayerPreview.php
===================================================================
--- trunk/mapbender/http/php/mb_metadata_uploadLayerPreview.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/php/mb_metadata_uploadLayerPreview.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -50,10 +50,12 @@
 
         $images_orig = ImageCreateFromJPEG($image);
         break;
+
     case 'jpeg':
 
         $images_orig = ImageCreateFromJPEG($image);
         break;
+
     case 'png':
 
         $images_orig = ImageCreateFrompng($image);
@@ -78,7 +80,7 @@
     // create new image with the calculated size
     $images_target = ImageCreateTrueColor(200, 200);
     //fill the new image with transparency background
-    $color = imagecolorallocatealpha($images_target, 255, 255, 255, 0); //fill transparent back
+    $color = imagecolorallocatealpha($images_target, 255, 255, 255, 0); //fill white background
     imagefill($images_target, 0, 0, $color);
     imagealphablending( $images_target, false );
     imagesavealpha($images_target, true);
@@ -120,7 +122,7 @@
     // create new image with the calculated size
     $images_target = ImageCreateTrueColor(200, 200);
     //fill the new image with transparency background
-    $color = imagecolorallocatealpha($images_target, 255, 255, 255, 0); //fill transparent back
+    $color = imagecolorallocatealpha($images_target, 255, 255, 255, 0); //fill white background
     imagefill($images_target, 0, 0, $color);
     imagealphablending( $images_target, false );
     imagesavealpha($images_target, true);

Modified: trunk/mapbender/http/php/mod_GetPublishedData.php
===================================================================
--- trunk/mapbender/http/php/mod_GetPublishedData.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/php/mod_GetPublishedData.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -1,4 +1,6 @@
 <?php
+ini_set('display_errors', 'On');
+error_reporting(E_ALL);
 
 /**
  * @version   Changed: ### 2015-02-23 14:00:42 UTC ###
@@ -46,72 +48,58 @@
 }
 // create and numerically indexed array
 $kmls = array_values($myWmc->generalExtensionArray["KMLS"]);
-//parse the geojson from the array
-$geoJson = $kmls[0]["data"];
+
 //create the fileName
 $file = "myDataCollection.".$outputFormat;
-// set headers to force the download
-header("Content-Disposition: attachment; filename=" . urlencode($file));
-header("Content-Type: application/force-download");
-header("Content-Type: application/octet-stream");
-header("Content-Type: application/download");
 
+if (sizeof($kmls) > 1) {
+    # create a file for each featureCollection and push them in a zip
 
-// handle the different outputformat
-if ($outputFormat == 'geojson') {
-    // create the json-file
-    $geoJsonFile = '../tmp/myDataCollection.geojson';
-    // put the contents to the created file
-    file_put_contents($geoJsonFile, json_encode($geoJson));
-    // create a string from the created file
-    $fileString = file_get_contents('../tmp/myDataCollection.geojson');
-    // return the string
-    echo $fileString;
-    die;
+    $zip = new ZipArchive;
+    $zipName = '../tmp/myDataCollection.zip';
+    $fileName = "myDataCollection.zip";
 
-}elseif ($outputFormat == 'gpx') {
-    //convert geojson to kml
+    if ($zip->open($zipName, ZIPARCHIVE::CREATE)=== TRUE) {
+        // counting filenames
+        $fileCounter = 1;
+        // loop over every featureCollection
+        foreach ($kmls as $key => $value) {
 
-    //create the geojson-file temporary
-    $temp_geojson = '../tmp/myDataCollection.geojson';
-    // write the file
-    file_put_contents($temp_geojson,json_encode($geoJson));
-    //transform the geojson to kml
-    $unique = '../tmp/myDataCollection';
-    $fGeojson = $unique.".geojson";
-    $fKml = $unique.".kml";
-    $pathOgr = '/usr/bin/ogr2ogr';
-    // execute ogr2ogr
-    $exec = $pathOgr.' -f KML '.$fKml.' '.$fGeojson;
-    exec(escapeshellcmd($exec));
-    //enter location of KML file here
-    $kml = "../tmp/myDataCollection.kml";
-    // create gpx from kml
-    kml_to_gpx($kml);
-    die;
+            $geoJson = $kmls[$fileCounter-1]["data"];
+            $dataFile = createFile($outputFormat,$geoJson);
+            $zip->addFromString('myFeatureCollection_'.$fileCounter.'.'.$outputFormat,$dataFile);
+            // increment the counter
+            $fileCounter +=1;
 
-}elseif ($outputFormat == 'kml') {
-    //convert geojson to kml
+        }
 
-    //create the geojson-file temporary
-    $temp_geojson = '../tmp/myDataCollection.geojson';
-    // write the file
-    file_put_contents($temp_geojson,json_encode($geoJson));
-    //transform the file to kml
-    $unique = '../tmp/myDataCollection';
-    $fGeojson = $unique.".geojson";
-    $fKml = $unique.".kml";
-    $pathOgr = '/usr/bin/ogr2ogr';
-    //execute ogr2ogr to transfrom json to kml
-    $exec = $pathOgr.' -f KML '.$fKml.' '.$fGeojson;
-    exec(escapeshellcmd($exec));
-    // create string from kml-file
-    $fileString = file_get_contents('../tmp/myDataCollection.kml');
-    //return the string
-    echo $fileString;
-    die;
+        $zip->close();
+    }
+// set the headers to return a zip to the client
+header('Content-Type: application/zip');
+header('Content-Disposition: attachment; filename="'.$filename.'"');
+header('Content-Length: '.filesize($zipName) );
+
+readfile($zipName);
+
+//remove zip from harddisk
+exec(escapeshellcmd('rm ../tmp/myDataCollection.zip'));
+die;
+
+} else {
+    // set headers to force the download for a single file
+    header("Content-Disposition: attachment; filename=" . urlencode($file));
+    header("Content-Type: application/force-download");
+    header("Content-Type: application/octet-stream");
+    header("Content-Type: application/download");
+    //parse the geojson from the array
+    $geoJson = $kmls[0]["data"];
+    $dataFile = createFile($outputFormat,$geoJson);
+    echo $dataFile;
+
 }
 
+
 /**
  * converts a kml-file into a gpx-file
  * @param  string $u the file location
@@ -171,7 +159,7 @@
         // placemarks
         $names = array();
         foreach ($dom_kml->getElementsByTagName('Placemark') as $placemark) {
-            //name
+            // var_dump('sdafsdaf');
             foreach ($placemark->getElementsByTagName('name') as $name) {
                 $name  = $name->nodeValue;
                 //check if the key exists
@@ -276,9 +264,50 @@
                     }
                 }
             }
+             foreach ($placemark->getElementsByTagName('Polygon') as $lineString) {
+                foreach ($lineString->getElementsByTagName('coordinates') as $coordinates) {
+                    //add the new track
+                    $gpx_trk = $dom_gpx->createElement('trk');
+                    $gpx_trk = $gpx->appendChild($gpx_trk);
+
+                    $gpx_name = $dom_gpx->createElement('name');
+                    $gpx_name = $gpx_trk->appendChild($gpx_name);
+                    $gpx_name_text = $dom_gpx->createTextNode($name);
+                    $gpx_name->appendChild($gpx_name_text);
+
+                    $gpx_trkseg = $dom_gpx->createElement('trkseg');
+                    $gpx_trkseg = $gpx_trk->appendChild($gpx_trkseg);
+
+                    $coordinates = $coordinates->nodeValue;
+                    $coordinates = preg_split("/[\s\r\n]+/", $coordinates); //split the coords by new line
+                    foreach ($coordinates as $coordinate) {
+                        $latlng = explode(",", $coordinate);
+
+                        if (($lat = $latlng[1]) && ($lng = $latlng[0])) {
+                            $gpx_trkpt = $dom_gpx->createElement('trkpt');
+                            $gpx_trkpt = $gpx_trkseg->appendChild($gpx_trkpt);
+
+                            $gpx_trkpt_lat = $dom_gpx->createAttribute('lat');
+                            $gpx_trkpt->appendChild($gpx_trkpt_lat);
+                            $gpx_trkpt_lat_text = $dom_gpx->createTextNode($lat);
+                            $gpx_trkpt_lat->appendChild($gpx_trkpt_lat_text);
+
+                            $gpx_trkpt_lon = $dom_gpx->createAttribute('lon');
+                            $gpx_trkpt->appendChild($gpx_trkpt_lon);
+                            $gpx_trkpt_lon_text = $dom_gpx->createTextNode($lng);
+                            $gpx_trkpt_lon->appendChild($gpx_trkpt_lon_text);
+
+                            $gpx_time = $dom_gpx->createElement('time');
+                            $gpx_time = $gpx_trkpt->appendChild($gpx_time);
+                            $gpx_time_text = $dom_gpx->createTextNode(utcdate());
+                            $gpx_time->appendChild($gpx_time_text);
+                        }
+                    }
+                }
+            }
         }
         header("Content-Type: text/xml");
-        echo $dom_gpx->saveXML();
+        return $dom_gpx->saveXML();
     }
 
 }
@@ -291,3 +320,63 @@
 function utcdate() {
         return gmdate("Y-m-d\Th:i:s\Z");
 }
+
+function createFile ($outputFormat, $geoJson) {
+
+    // handle the different outputformat
+if ($outputFormat == 'geojson') {
+    // create the json-file
+    $geoJsonFile = '../tmp/myDataCollection.geojson';
+    // put the contents to the created file
+    file_put_contents($geoJsonFile, json_encode($geoJson));
+    // create a string from the created file
+    $fileString = file_get_contents('../tmp/myDataCollection.geojson');
+    // return the string
+    return $fileString;
+    die;
+
+}elseif ($outputFormat == 'gpx') {
+    //convert geojson to kml
+
+    //create the geojson-file temporary
+    $temp_geojson = '../tmp/myDataCollection.geojson';
+    // write the file
+    file_put_contents($temp_geojson,json_encode($geoJson));
+    //transform the geojson to kml
+    $unique = '../tmp/myDataCollection';
+    $fGeojson = $unique.".geojson";
+    $fKml = $unique.".kml";
+    $pathOgr = '/usr/bin/ogr2ogr';
+    // execute ogr2ogr
+    $exec = $pathOgr.' -f KML '.$fKml.' '.$fGeojson;
+    exec(escapeshellcmd($exec));
+    //enter location of KML file here
+    $kml = "../tmp/myDataCollection.kml";
+    // create gpx from kml
+    return kml_to_gpx($kml);
+    die;
+
+}elseif ($outputFormat == 'kml') {
+    //convert geojson to kml
+
+    //create the geojson-file temporary
+    $temp_geojson = '../tmp/myDataCollection.geojson';
+    // write the file
+    file_put_contents($temp_geojson,json_encode($geoJson));
+    //transform the file to kml
+    $unique = '../tmp/myDataCollection';
+    $fGeojson = $unique.".geojson";
+    $fKml = $unique.".kml";
+    $pathOgr = '/usr/bin/ogr2ogr';
+    //execute ogr2ogr to transfrom json to kml
+    $exec = $pathOgr.' -f KML '.$fKml.' '.$fGeojson;
+    exec(escapeshellcmd($exec));
+    // create string from kml-file
+    $fileString = file_get_contents('../tmp/myDataCollection.kml');
+    //return the string
+
+    return $fileString;
+    die;
+}
+
+}

Modified: trunk/mapbender/http/php/transformgeojson.php
===================================================================
--- trunk/mapbender/http/php/transformgeojson.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/php/transformgeojson.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -21,6 +21,7 @@
 header("Content-Type: application/json");
 
 $json = file_get_contents("php://input");
+// var_dump($json);die;
 try {
 
     $json = json_decode($json);

Modified: trunk/mapbender/http/php/uploadKml.php
===================================================================
--- trunk/mapbender/http/php/uploadKml.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/php/uploadKml.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -23,12 +23,12 @@
 
 $kml = new KML();
 $content = file_get_contents($_FILES['kml']['tmp_name']);
-
 try {
     if(preg_match('/.kml$/', $_FILES['kml']['name'])) {
         header("Content-Type: text/plain");
         if($kml->parseKml($content)){
-            $geojson  =  $kml->toGeoJSON();
+            $geojson  =  $kml->createGeoJSON();
+            // var_dump($geojson);die;
             echo $geojson;
         }else{
             echo("{}");
@@ -36,9 +36,11 @@
     }
     if(preg_match('/.(json|geojson)$/', $_FILES['kml']['name'])) {
         header("Content-Type: text/plain");
+        // var_dump($content);die;
         echo $content;
     }
     if(preg_match('/.(xml|gpx)$/', $_FILES['kml']['name'])) {
+        // var_dump($content);die;
         header("Content-Type: text/plain");
         echo $content;
     }

Modified: trunk/mapbender/http/plugins/kmlTree.js
===================================================================
--- trunk/mapbender/http/plugins/kmlTree.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/plugins/kmlTree.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -160,9 +160,9 @@
                                         $('#dataExportDialog').remove();
                                     }
                                 });
-                                var exportHtmlsdfdsf = '<div id="exportHtml">' + '<form>' + '<label class="export-format-kml">KML<input type="radio" name="export-format" value="kml" checked="checked"></input></label>' + '<label class="export-format-kml">KML<input type="radio" name="export-format" value="kml" checked="checked"></input></label>' + '<label class="export-format-kml">KML<input type="radio" name="export-format" value="kml" checked="checked"></input></label><br><br>' +
-                                    '<img src="../img/osgeo_graphics/geosilk/link22.png"/>' + '<label class="export-format-gpx">GPX</label>' + '<label class="export-format-geojson">geoJSON</label><br></br>' +
-                                    '<a download="myfeatures.kml" href="#" class="digitize-image digitize-export" style="float: left;"></a>' + '</form>' + '</div>';
+                                // var exportHtmlsdfdsf = '<div id="exportHtml">' + '<form>' + '<label class="export-format-kml">KML<input type="radio" name="export-format" value="kml" checked="checked"></input></label>' + '<label class="export-format-kml">KML<input type="radio" name="export-format" value="kml" checked="checked"></input></label>' + '<label class="export-format-kml">KML<input type="radio" name="export-format" value="kml" checked="checked"></input></label><br><br>' +
+                                //     '<img src="../img/osgeo_graphics/geosilk/link22.png"/>' + '<label class="export-format-gpx">GPX</label>' + '<label class="export-format-geojson">geoJSON</label><br></br>' +
+                                //     '<a download="myfeatures.kml" href="#" class="digitize-image digitize-export" style="float: left;"></a>' + '</form>' + '</div>';
                                 var exportHtml = '<div id="exportHtml"><table><tbody>' +
                                     '<tr><td>KML:</td><td><label class="export-format-kml exportDatasetIcon" style="padding-top:11px;"></label></td><td class="exportDataLink kml" wmcId="'+wmc_id+'"outputFormat="kml"><img src="../img/osgeo_graphics/geosilk/link22.png"/></td></tr>' +
                                     '<tr><td>GPX:</td><td><label class="export-format-gpx exportDatasetIcon" style="padding-top:11px;"></label></td><td class="exportDataLink gpx" wmcId="'+wmc_id+'"outputFormat="gpx"><img src="../img/osgeo_graphics/geosilk/link22.png"/></td></tr>' +
@@ -539,10 +539,10 @@
             });
             $('#kml-load-tabs').tabs();
             $('#kml-load-tabs').find('button.add').bind('click', function() {
-                $('#mapframe1').kml({
+                $('#mapframe1').kml({ //TODO: what is happening?
                     url: $('#kml-load-tabs').find('.kmlurl').val()
                 });
-                $(dlg).dialog('destroy');
+                // $(dlg).dialog('destroy');
             });
             $('#kml-load-tabs').find('button.add-kml').bind('click', function() {
                 var kml = $('#mapframe1').data('kml');
@@ -550,30 +550,42 @@
                 if (title == '') {
                     return;
                 }
-                kml.addLayer(title, {
-                    features: [],
-                    type: 'FeatureCollection'
+                kml.addLayer(title,{
+                    "@context": {uuid: UUID.genV4().toString(), created: new Date().toISOString() ,title: title, updated: new Date().toISOString()},
+                    type: 'FeatureCollection',
+                    features: []
                 });
                 $(dlg).dialog('destroy');
             });
             var ifr = $('iframe[name="kml-upload-target"]')[0];
             var onloadfun = function() {
                 ifr.onload = null;
-                var txt = $(this).contents().find('pre').text();
+                var txt = $(this).contents().find('pre').text(); // result von uploadKML.php
                 var data;
                 try {
                     data = JSON.parse(txt);
+
                 } catch (e) {
+
                     var xml = new DOMParser().parseFromString(txt, 'application/xml');
                     data = toGeoJSON.gpx(xml);
                 }
                 var kml = $('#mapframe1').data('kml');
-                var name = $('#kml-from-upload input[type="file"]').val();
-                if (name.match(/[\\]([^\\]+)/g)) {
-                    name = name.match(/[\\]([^\\]+)/g);
+                var name;
+                if(data.hasOwnProperty('@context')){
+
+                    name = data['@context']['title'];
+                    kml.addLayer(name, data);
+               }else{
+
+                    name = $('#kml-from-upload input[type="file"]').val();
+                    if (name.match(/[\\]([^\\]+)/g)) {
+                        name = name.match(/[\\]([^\\]+)/g);
+                    }
+                    name = name[name.length - 1];
+                    kml.addLayer(name, data);
                 }
-                name = name[name.length - 1];
-                kml.addLayer(name, data);
+
                 $(dlg).dialog('destroy');
             };
             $('#kml-from-upload form').bind('submit', function() {
@@ -604,7 +616,6 @@
     o.$target.bind('kml:loaded', function(e, obj) {
         //console.log(obj);
         var checked = obj.display ? 'checked="checked"' : '';
-
         title = obj.url;
         if (obj.refreshing) {
             $KMLfolder.find('ul li[title="' + title + '"]').remove();
@@ -627,7 +638,22 @@
             if (multi) {
                 toggle = '<button class="toggle" name="toggle" value="toggle"></button>';
             }
-            title = obj.data.features[i].properties.name;
+
+            if(obj.data.features[i].properties.name){
+
+                title = obj.data.features[i].properties.name;
+
+            } else if(obj.data.features[i].properties.title) {
+
+                title = obj.data.features[i].properties.title;
+            } else  {
+
+                title = 'Title undefined';
+
+            }
+                // title = obj.data.features[i].properties.name;
+
+
             abbrevTitle = title.length < 20 ? title : title.substr(0, 17) + "...";
             var displ = obj.data.features[i].display === true || obj.data.features[i].display === undefined;
             $feature = $('<li idx="' + i + '" title="' + title + '"><button class="digitize-menu-arrow"></button>' + toggle + '<input type="checkbox" ' + (displ ? 'checked="checked"' : '') + '/><div class="style-preview" style="width: 20px; height: 20px; display: inline;"></div><a href="#" >' + abbrevTitle + '</a></li>');

Modified: trunk/mapbender/http/plugins/mb_digitize_widget.php
===================================================================
--- trunk/mapbender/http/plugins/mb_digitize_widget.php	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/plugins/mb_digitize_widget.php	2015-03-09 12:43:13 UTC (rev 9163)
@@ -569,7 +569,8 @@
         return function() {
 
             if ($(this).hasClass('editFeatureCollection')) {
-
+                    // kml = $('#mapframe1').data('kml');
+                    var oldCollectionName = feature['@context'].title;
                     var featureCollAttrDlg = $('<div id="featureCollAttrDlg"></div>').dialog({
                         title: "Featurecollection attributes ",// of "+ url,
                         width: 400,
@@ -587,17 +588,65 @@
 
                     var featureCollectionContent = "<div class='digitize-image digitize-style'></div>"+
                                                     "<br><br>"+
-                                                    "<div><table>"+
-                                                    "<tr><td>uuid</td><td><input type='text' value='test'/></td></tr>"+
-                                                    "<tr><td>title</td><td><input type='text' value='test'/></td></tr>"+
-                                                    "<tr><td>created</td><td><input type='text' value='test'/></td></tr>"+
-                                                    "<tr><td>updated</td><td><input type='text' value='test'/></td></tr>"+
+                                                    "<div><table id='featureCollTbl'>"+
+                                                    // "<tr><td>uuid</td><td><input type='text' name='uuid' value='"+feature['@context'].uuid+"'/></td></tr>"+
+                                                    // "<tr><td>title</td><td><input type='text' name='title' value='"+feature['@context'].title+"'/></td></tr>"+
+                                                    // "<tr><td>created</td><td><input type='text' name='created' value='"+feature['@context'].created+"'/></td></tr>"+
+                                                    // "<tr><td>updated</td><td><input type='text' name='updated' value='"+feature['@context'].updated+"'/></td></tr>"+
                                                     "</table></div>"+
                                                     "<br><br/>"+
                                                     "<div class='digitize-image digitize-add'></div>"+
                                                     "<div class='digitize-image digitize-save'></div>";
                     $('#featureCollAttrDlg').append(featureCollectionContent);
+                    $.each(feature['@context'], function(index, val) {
 
+                         $('#featureCollTbl').append("<tr><td>"+index+"</td><td><input type='text' name='"+index+"' value='"+val+"'/></td></tr>");
+                    });
+                    featureCollAttrDlg.find('.digitize-save').bind('click', function() {
+                    featureCollAttrDlg.find('table input').each(function() {
+                        var k = $(this).attr('name');
+                        var v = $(this).val();
+                        if(k) {
+                            feature['@context'][k] = v;
+                        }
+                    });
+                    feature['@context'].updated = new Date().toISOString();
+                    // save the changed feature in a new object
+                    if ( $('#mapframe1').data('kml')._kmls[oldCollectionName].url != $('#mapframe1').data('kml')._kmls[oldCollectionName].data['@context'].title ) {
+
+                        $('#mapframe1').data('kml')._kmls[feature['@context'].title] = $('#mapframe1').data('kml')._kmls[oldCollectionName];
+                        $('#mapframe1').data('kml')._kmls[feature['@context'].title].url = $('#mapframe1').data('kml')._kmls[feature['@context'].title].data['@context'].title;
+                        kml.remove(url);
+                        $("#kmlTree>li>ul>li[title='"+url+"']").remove();
+                        url =  $('#mapframe1').data('kml')._kmls[feature['@context'].title].url;
+                        featureCollAttrDlg.dialog('close');
+                        editDialog.dialog('close');
+                        kml.refresh(url);
+                    } else {
+
+                        featureCollAttrDlg.dialog('close');
+                        editDialog.dialog('close');
+                        kml.refresh(url);
+
+                    }
+                // var preview = attributesDialog.find('.digitize-preview').html('').get(0);
+                // kml.renderPreview(feature, preview);
+                });
+
+                // add row
+                    featureCollAttrDlg.find('.digitize-add').bind('click', function() {
+                    var newRow = $('<tr><td><input type="text"></input></td><td><input class="newInputValue" name="" type="text"></input></td></tr>');
+                    $(newRow).find('.newInputValue').bind('keyup',function(){
+                        $(this).attr('name',$(this).val());
+                    });
+                    featureCollAttrDlg.find('table').append(newRow);
+                    newRow.find('input').first().bind('change', function() {
+                        newRow.find('input').last().attr('name', $(this).val());
+                    });
+                });
+
+
+
             }else{
 
                 attributesDialog.dialog('open');
@@ -628,6 +677,8 @@
                         }
                     });
                     feature.properties.updated = new Date().toISOString();
+                    //get parent and change updated
+                    $('#mapframe1').data('kml')._kmls[url].data['@context'].updated = new Date().toISOString();
 
                     attributesDialog.dialog('close');
                     editDialog.dialog('close');
@@ -773,7 +824,8 @@
             // get the featureCollection data
             var url = $link.parent().attr('title');
             var featureCollection = $('#mapframe1').data('kml')._kmls[url].data;
-            digitizeDialog.find('.digitize-attributes').bind('click', editAttributes(featureCollection, kml, url));
+            var kml = $('#mapframe1').data('kml');
+            digitizeDialog.find('.digitize-attributes').bind('click',editAttributes(featureCollection, kml , url));
 
             digitizeDialog.find('.digitize-remove').bind('click', function() {
                 var kml = $('#mapframe1').data('kml');

Modified: trunk/mapbender/http/plugins/mb_loadkmlgeorss.js
===================================================================
--- trunk/mapbender/http/plugins/mb_loadkmlgeorss.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/http/plugins/mb_loadkmlgeorss.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -2,27 +2,27 @@
  * Package: load_georsskml
  *
  * Description:
- * This element enables you to load GeoRSS or KML temporary to a Mapbender application. 
- * The features will be displayed in the mapframe. The result will also be displayed in a result table. 
+ * This element enables you to load GeoRSS or KML temporary to a Mapbender application.
+ * The features will be displayed in the mapframe. The result will also be displayed in a result table.
  * The module enables you to load more than one GeoRSS/KML. Every resultset will be displayed in a result table.
  * As long as the result table is open. The features are shown in the map.
- * 
+ *
  * Files:
  *  - ../http/plugins/mb_loadkmlgeorss.js>
  *
  * SQL:
- * > INSERT INTO gui_element(fkey_gui_id, e_id, e_pos, e_public, e_comment, e_title, e_element, 
- * > e_src, e_attributes, e_left, e_top, e_width, e_height, e_z_index, e_more_styles, e_content, 
+ * > INSERT INTO gui_element(fkey_gui_id, e_id, e_pos, e_public, e_comment, e_title, e_element,
+ * > e_src, e_attributes, e_left, e_top, e_width, e_height, e_z_index, e_more_styles, e_content,
  * > e_closetag, e_js_file, e_mb_mod, e_target, e_requires, e_url) VALUES('<application_name>',
  * >'load_georsskml',2,1,'','Load GeoRSS or KML','img','../img/georss_logo_off.png','',750,10,
  * > 24,24,NULL ,'','','','../plugins/mb_loadkmlgeorss.js','','','','');
- * > 
- * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, context, var_type) 
- * > VALUES('<application_name>', 'load_georsskml', 'buffer', '100', 
+ * >
+ * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, context, var_type)
+ * > VALUES('<application_name>', 'load_georsskml', 'buffer', '100',
  * > 'how much space to leave around a feature when zooming to it ' ,'var');
  * >
- * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, context, var_type) 
- * > VALUES('<application_name>', 'load_georsskml', 'position', '', 
+ * > INSERT INTO gui_element_vars(fkey_gui_id, fkey_e_id, var_name, var_value, context, var_type)
+ * > VALUES('<application_name>', 'load_georsskml', 'position', '',
  * > 'position where the result frame is displayed, see the [http://docs.jquery.com/UI/Dialog |jquery UI documentation] for possible values' ,'var');
  *
  * Help:
@@ -30,20 +30,20 @@
  *
  * Maintainer:
  * http://www.mapbender.org/User:Karim_Malhas
- * 
+ *
  * Parameters:
  * buffer    - *[optional]* var, how much space to leave around a feature when zooming to it
  * position  - *[optional]* var, position where the result frame is displayed
- * 
  *
+ *
  * Requires:
  * <>
  * <>
- * 
+ *
  * License:
  * Copyright (c) 2009, Open Source Geospatial Foundation
- * This program is dual licensed under the GNU General Public License 
- * and Simplified BSD license.  
+ * This program is dual licensed under the GNU General Public License
+ * and Simplified BSD license.
  * http://svn.osgeo.org/mapbender/trunk/mapbender/license/license.txt
  */
 options.buffer = options.buffer || 0.10;
@@ -85,13 +85,13 @@
                 autoOpen: false,
                 height: 240,
                 width: 400,
-                buttons: { 
+                buttons: {
 					"OK" : function(){
 						var url = $('#' + options.id + '_url').val();
 						$('#' + options.id + '_url').val("");
 						var $dialog = $(this);
 						$dialog.dialog("close");
-				
+
 						var format = $("input:checked",$dialog).val();
 						var endpointURL = "";
 						if( format == "GeoRSS"){
@@ -104,7 +104,6 @@
 							type: "POST",
 							dataType: "json",
 							success: function(data,textStatus,xhr){
-						
 							if(data.errorMessage){
 								$("<div class='labelLoadError'>"+ translatedI18nObject.labelLoadError +"<div>").dialog({ buttons: {"OK":function(){ $(this).dialog("close"); } } } );
 								return;
@@ -125,8 +124,8 @@
 								var map = $('#mapframe1').mapbender();
 								//title = feature.properties.title || feature.properties.name || translatedI18nObject.labelUntitled;
 
-							
-								
+
+
 								var geomArray = new GeometryArray();
 								var highlightArray = [];
 								geomArray.importGeoJSON(data);
@@ -140,10 +139,10 @@
 									icon = g.e.getElementValueByName("Mapbender:icon");
 									title = g.e.getElementValueByName("title");
 									name = g.e.getElementValueByName("name");
-									
+
 									if(name != "false" && name !== false){
 										title = name;
-									}			
+									}
 									if(icon == "false" || icon === false){
 										g.e.setElement("Mapbender:iconOffsetX", -10);
 										g.e.setElement("Mapbender:iconOffsetY", -34);
@@ -203,17 +202,17 @@
 								}
 							});
 							$tableDialog.append($table);
-							
+
 							$table.dataTable({"bJQueryUI": true ,
 								"oLanguage":{
 									"sUrl":"../extensions/dataTables-1.5/lang/"+Mapbender.languageId +".txt"
 									} });
-							
 
+
 							$dialog.dialog('close');
 							},
 							error: function(xhr, ajaxOptions,error){
-								$("<div class='labelLoadError'>"+ translatedI18nObject.labelLoadError +"</div>").dialog({ buttons: {"OK":function(){ $(this).dialog("close");  }} });	
+								$("<div class='labelLoadError'>"+ translatedI18nObject.labelLoadError +"</div>").dialog({ buttons: {"OK":function(){ $(this).dialog("close");  }} });
 							}
 						});
 					},
@@ -224,8 +223,8 @@
 });
 Mapbender.events.localize.register(function(){
 	Mapbender.modules.i18n.queue(options.id, originalI18nObject, function(translatedI18nObject){
-		$('.labelLoadError').text(translatedI18nObject.labelLoadError); 
-		$('.labelUrlBox').text(translatedI18nObject.labelUrlBox); 
+		$('.labelLoadError').text(translatedI18nObject.labelLoadError);
+		$('.labelUrlBox').text(translatedI18nObject.labelUrlBox);
 	});
 });
 
@@ -235,7 +234,7 @@
 	});
 	$('#mapframe1').click(function(e){
 		var map = $('#mapframe1').mapbender();
-		var pos = map.getMousePosition(e);		
+		var pos = map.getMousePosition(e);
 		var clickPoint =  map.convertPixelToReal(new Point(pos.x,pos.y));
 		var feed = null;
 		var requestGeometries = [];
@@ -243,7 +242,7 @@
 		// - Points are represented as icons, so we check if the click is on an icon
 		// - Polygons don't have a dom Element when not using Rapheljs, so we go ask postgis
 		// after that's finished the results are merged and displayed in a box
-		var pointGeometries = {};	
+		var pointGeometries = {};
 		var g,h,nodes = null;
 		for (var i in that.feeds){
 			feed = that.feeds[i] ;
@@ -251,12 +250,12 @@
 
 			for(var j = 0; j < feed.geomArray.count(); j++){
 				g = feed.geomArray.get(j);
-			 	h = feed.highlightArray[j];	
+			 	h = feed.highlightArray[j];
 			 	nodes = h.getNodes();
 				if(g.geomType == geomType.point){
 					// we only add one point per highlight so we can assume there's only one node
 					if(!nodes[0]){ continue;}
-					var rect = nodes[0].getBoundingClientRect(); 
+					var rect = nodes[0].getBoundingClientRect();
 					if(e.clientX >= rect.left && e.clientX <= rect.right &&
 					   e.clientY >= rect.top  && e.clientY <= rect.bottom){
 						// we just need the keys to exist
@@ -264,7 +263,7 @@
 						// server
 						pointGeometries[j] = true;
 					}
-					
+
 				}else{
 					requestGeometries.push(g.toText());
 				}
@@ -287,7 +286,7 @@
 					return;
 				}
 
-				
+
 				$("*",that.$popup).remove();
 				var $tabs = $("<ul></ul>");
 				// this iterates over an object where the keys are _not_ the incremential
@@ -318,13 +317,13 @@
 				if(j > 1){
 					var $tabcontainer = $("<div><div>");
 					$tabcontainer.append($tabs);
-					$tabcontainer.append($('div',that.$popup));	
+					$tabcontainer.append($('div',that.$popup));
 					that.$popup.append($tabcontainer);
 					$tabcontainer.tabs();
 				}
 				that.$popup.dialog('open');
-			
 
+
 			}})(feed.geomArray, pointGeometries)
 			});
 			req.send();

Modified: trunk/mapbender/lib/mb.ui.displayKmlFeatures.js
===================================================================
--- trunk/mapbender/lib/mb.ui.displayKmlFeatures.js	2015-03-02 13:27:54 UTC (rev 9162)
+++ trunk/mapbender/lib/mb.ui.displayKmlFeatures.js	2015-03-09 12:43:13 UTC (rev 9163)
@@ -1,26 +1,26 @@
 // events
-// 	geojson:loaded  	- a georssfeed was loaded from a server and is now available: function(url,geojson)
-// 	georss:error	- a georssfeed failed to load: function(url,error);
+//  geojson:loaded      - a georssfeed was loaded from a server and is now available: function(url,geojson)
+//  georss:error    - a georssfeed failed to load: function(url,error);
 
 var originalI18nObject = {
-    "labelLoadError" : "Could not load Document",
-    "labelName":"Name",
-    "labelUntitled":"Untitled",
+    "labelLoadError": "Could not load Document",
+    "labelName": "Name",
+    "labelUntitled": "Untitled",
     "labelUrlBox": "Paste URL here",
-    "sProcessing":   "Processing...",
-    "sLengthMenu":   "Show _MENU_ entries",
-    "sZeroRecords":  "No matching records found",
-    "sInfo":         "SLowing _START_ to _END_ of _TOTAL_ entries",
-    "sInfoEmpty":    "Showing 0 to 0 of 0 entries",
+    "sProcessing": "Processing...",
+    "sLengthMenu": "Show _MENU_ entries",
+    "sZeroRecords": "No matching records found",
+    "sInfo": "SLowing _START_ to _END_ of _TOTAL_ entries",
+    "sInfoEmpty": "Showing 0 to 0 of 0 entries",
     "sInfoFiltered": "(filtered from _MAX_ total entries)",
-    "sInfoPostFix":  "",
-    "sSearch":       "Search:",
-    "sUrl":          "",
+    "sInfoPostFix": "",
+    "sSearch": "Search:",
+    "sUrl": "",
     "oPaginate": {
-        "sFirst":    "First",
+        "sFirst": "First",
         "sPrevious": "Previous",
-        "sNext":     "Next",
-        "sLast":     "Last"
+        "sNext": "Next",
+        "sLast": "Last"
     }
 };
 
@@ -45,34 +45,33 @@
     _kmls: {},
     cache: {},
     kmlOrder: [],
-    _popup : null,
+    _popup: null,
     creatingPhase: true,
     selectedFeatures: [],
-    selectionDialog: '<div id="selection-dialog" title="Selected features">'
-                   + '<ul id="selected-features-list">'
-                   + '</ul>'
-                   + '<div class="digitize-image digitize-remove"></div>'
-                   + '<div class="digitize-image digitize-export"></div>'
-                   + '</div>',
+    selectionDialog: '<div id="selection-dialog" title="Selected features">' + '<ul id="selected-features-list">' + '</ul>' + '<div class="digitize-image digitize-remove"></div>' + '<div class="digitize-image digitize-export"></div>' + '</div>',
 
-    _create: function(){
-        var self = this, o = this.options;
-        this.element.mapbender().events.afterMapRequest.register(function () {
+    _create: function() {
+        var self = this,
+            o = this.options;
+        this.element.mapbender().events.afterMapRequest.register(function() {
             self.render();
         });
 
         this.element.bind('click', function(e) {
-            if(self.lastWasBox) {
+            if (self.lastWasBox) {
                 self.lastWasBox = false;
                 return;
             }
             var map = self.element.mapbender();
             var pos = map.getMousePosition(e);
-            var clickPoint =  map.convertPixelToReal(new Point(pos.x,pos.y));
-            var wgspt = Proj4js.transform(self.targetProj, self.wgs84, {x: clickPoint.x, y: clickPoint.y});
+            var clickPoint = map.convertPixelToReal(new Point(pos.x, pos.y));
+            var wgspt = Proj4js.transform(self.targetProj, self.wgs84, {
+                x: clickPoint.x,
+                y: clickPoint.y
+            });
             var res = map.getScale() / mb_resolution / 100;
 
-            if(!self.queriedLayer) return;
+            if (!self.queriedLayer) return;
 
             var matchedIds = self.findFeatures(pos);
 
@@ -82,63 +81,68 @@
         var boxfun;
 
         this.element.bind('mousedown', boxfun = function(e) {
-                                           if(!self.queriedLayer) return;
-                                           var box = new Mapbender.Box({
-                                               target: 'mapframe1'
-                                           });
-                                           box.start(e);
-                                           $('#mapframe1').css("cursor", "crosshair")
-                                           .mouseup(function (e) {
-                                               box.stop(e, function (extent) {
-                                                   if (typeof extent === "undefined") {
-                                                       return;
-                                                   }
+            if (!self.queriedLayer) return;
+            var box = new Mapbender.Box({
+                target: 'mapframe1'
+            });
+            box.start(e);
+            $('#mapframe1').css("cursor", "crosshair")
+                .mouseup(function(e) {
+                    box.stop(e, function(extent) {
+                        if (typeof extent === "undefined") {
+                            return;
+                        }
 
-                                                   var matchedIds = self.findFeatures(extent);
-                                                   self.updateSelectedFeatures(matchedIds, e.ctrlKey);
-                                                   self.lastWasBox = true;
+                        var matchedIds = self.findFeatures(extent);
+                        self.updateSelectedFeatures(matchedIds, e.ctrlKey);
+                        self.lastWasBox = true;
 
-                                                   $('#mapframe1')
-                                                   .css("cursor", "default")
-                                                   .unbind("mousedown")
-                                                   .unbind("mouseup")
-                                                   .unbind("mousemove")
-                                                   .bind('mousedown', boxfun);
-                                               });
-                                               return false;
-                                           });
-                                       });
+                        $('#mapframe1')
+                            .css("cursor", "default")
+                            .unbind("mousedown")
+                            .unbind("mouseup")
+                            .unbind("mousemove")
+                            .bind('mousedown', boxfun);
+                    });
+                    return false;
+                });
+        });
 
-        self.element.bind('kml:loaded',function(event,obj){
-            if(o.autoOpen){
+        self.element.bind('kml:loaded', function(event, obj) {
+            if (o.autoOpen) {
                 self.render();
             }
         });
-        self.element.bind('kml:error',function(event,message){
+        self.element.bind('kml:error', function(event, message) {
             alert(message);
         });
 
         var kmls = mb_getWmcExtensionData('KMLORDER');
-        if(kmls) {
+        if (kmls) {
             this.kmlOrder = JSON.parse(kmls);
         }
         kmls = mb_getWmcExtensionData('KMLS');
-        if(kmls) {
+        if (kmls) {
             kmls = JSON.parse(kmls);
             this._kmls = kmls;
-            for(var k in this.kmlOrder) {
+            for (var k in this.kmlOrder) {
                 kmls[this.kmlOrder[k]].loadedOnStartup = true;
-                self.element.trigger('kml:loaded',kmls[this.kmlOrder[k]]);
+                self.element.trigger('kml:loaded', kmls[this.kmlOrder[k]]);
             }
         }
         this.creatingPhase = false;
         this.render();
     },
 
-    _init: function(){
-        var self = this, o = this.options;
-        this._popup = $('<div></div>').dialog({autoOpen: false, height: 500, width: 500});
-        if(o.url){
+    _init: function() {
+        var self = this,
+            o = this.options;
+        this._popup = $('<div></div>').dialog({
+            autoOpen: false,
+            height: 500,
+            width: 500
+        });
+        if (o.url) {
             self._load(o.url);
         }
     },
@@ -150,24 +154,36 @@
         var map = self.element.mapbender();
         var ispoint;
         var clickPoint, wgspt, clickBox, min, max;
-        if(posOrBox.x) {
-            clickPoint =  map.convertPixelToReal(new Point(posOrBox.x,posOrBox.y));
-            wgspt = Proj4js.transform(self.targetProj, self.wgs84, {x: clickPoint.x, y: clickPoint.y});
+        if (posOrBox.x) {
+            clickPoint = map.convertPixelToReal(new Point(posOrBox.x, posOrBox.y));
+            wgspt = Proj4js.transform(self.targetProj, self.wgs84, {
+                x: clickPoint.x,
+                y: clickPoint.y
+            });
             ispoint = true;
         } else {
             clickBox = posOrBox;
-            min = Proj4js.transform(self.targetProj, self.wgs84, {x: clickBox.minx, y: clickBox.miny});
-            max = Proj4js.transform(self.targetProj, self.wgs84, {x: clickBox.maxx, y: clickBox.maxy});
+            min = Proj4js.transform(self.targetProj, self.wgs84, {
+                x: clickBox.minx,
+                y: clickBox.miny
+            });
+            max = Proj4js.transform(self.targetProj, self.wgs84, {
+                x: clickBox.maxx,
+                y: clickBox.maxy
+            });
             ispoint = false;
         }
         var res = map.getScale() / mb_resolution / 100;
 
         $.each(self._kmls, function(_, itm) {
             $.each(itm.data.features, function(k, v) {
-                if(ispoint) {
+                if (ispoint) {
                     self.matchFeatureToPoint(v, clickPoint, matchedIds, res, itm, wgspt, k);
                 } else {
-                    self.matchFeatureToBox(v, {min: min, max: max}, matchedIds, itm, k);
+                    self.matchFeatureToBox(v, {
+                        min: min,
+                        max: max
+                    }, matchedIds, itm, k);
                 }
             });
         });
@@ -180,53 +196,72 @@
     },
 
     matchFeatureToPoint: function(feat, clickPoint, matchedIds, res, itm, wgspt, idx) {
-        if(feat.geometry.type.match(/point/i)) {
-            var pt = Proj4js.transform(this.wgs84, this.targetProj, {x: feat.geometry.coordinates[0], y: feat.geometry.coordinates[1]});
+        if (feat.geometry.type.match(/point/i)) {
+            var pt = Proj4js.transform(this.wgs84, this.targetProj, {
+                x: feat.geometry.coordinates[0],
+                y: feat.geometry.coordinates[1]
+            });
             var minx = pt.x - 20 * res;
             var miny = pt.y - 20 * res;
             var maxx = minx + 40 * res;
             var maxy = miny + 40 * res;
-            if(minx < clickPoint.x && maxx > clickPoint.x && miny < clickPoint.y && maxy > clickPoint.y) {
-                matchedIds.push({url: itm.url, id: idx});
+            if (minx < clickPoint.x && maxx > clickPoint.x && miny < clickPoint.y && maxy > clickPoint.y) {
+                matchedIds.push({
+                    url: itm.url,
+                    id: idx
+                });
             }
         } else {
             var box = this.getBbox(feat);
-            if(this.inBox(box[0], box[1], box[2], box[3], wgspt.x, wgspt.y)) {
-                matchedIds.push({url: itm.url, id: idx});
+            if (this.inBox(box[0], box[1], box[2], box[3], wgspt.x, wgspt.y)) {
+                matchedIds.push({
+                    url: itm.url,
+                    id: idx
+                });
             }
         }
     },
 
     matchFeatureToBox: function(feat, wgsbox, matchedIds, itm, idx) {
-        if(feat.geometry.type.match(/point/i)) {
-            if(this.inBox(wgsbox.min.x, wgsbox.min.y, wgsbox.max.x, wgsbox.max.y, feat.geometry.coordinates[0], feat.geometry.coordinates[1])) {
-                matchedIds.push({url: itm.url, id: idx});
+        if (feat.geometry.type.match(/point/i)) {
+            if (this.inBox(wgsbox.min.x, wgsbox.min.y, wgsbox.max.x, wgsbox.max.y, feat.geometry.coordinates[0], feat.geometry.coordinates[1])) {
+                matchedIds.push({
+                    url: itm.url,
+                    id: idx
+                });
             }
         } else {
             var box = this.getBbox(feat);
-            if(this.inBox(box[0], box[1], box[2], box[3], wgsbox.min.x, wgsbox.min.y)
-             || this.inBox(box[0], box[1], box[2], box[3], wgsbox.min.x, wgsbox.max.y)
-             || this.inBox(box[0], box[1], box[2], box[3], wgsbox.max.x, wgsbox.max.y)
-             || this.inBox(box[0], box[1], box[2], box[3], wgsbox.max.x, wgsbox.min.y)) {
-                matchedIds.push({url: itm.url, id: idx});
+            if (this.inBox(box[0], box[1], box[2], box[3], wgsbox.min.x, wgsbox.min.y) || this.inBox(box[0], box[1], box[2], box[3], wgsbox.min.x, wgsbox.max.y) || this.inBox(box[0], box[1], box[2], box[3], wgsbox.max.x, wgsbox.max.y) || this.inBox(box[0], box[1], box[2], box[3], wgsbox.max.x, wgsbox.min.y)) {
+                matchedIds.push({
+                    url: itm.url,
+                    id: idx
+                });
                 return;
             }
-            if(wgsbox.min.x < box[0] && wgsbox.max.x > box[2]) {
-                if(wgsbox.min.y > box[1] && wgsbox.min.y < box[3]
-                 || wgsbox.max.y > box[1] && wgsbox.max.y < box[3]) {
-                    matchedIds.push({url: itm.url, id: idx});
+            if (wgsbox.min.x < box[0] && wgsbox.max.x > box[2]) {
+                if (wgsbox.min.y > box[1] && wgsbox.min.y < box[3] || wgsbox.max.y > box[1] && wgsbox.max.y < box[3]) {
+                    matchedIds.push({
+                        url: itm.url,
+                        id: idx
+                    });
                     return;
                 }
             }
-            if(wgsbox.min.y < box[1] && wgsbox.max.y > box[3]) {
-                if(wgsbox.min.x > box[0] && wgsbox.min.x < box[2]
-                 || wgsbox.max.x > box[0] && wgsbox.max.x < box[2]) {
-                    matchedIds.push({url: itm.url, id: idx});
+            if (wgsbox.min.y < box[1] && wgsbox.max.y > box[3]) {
+                if (wgsbox.min.x > box[0] && wgsbox.min.x < box[2] || wgsbox.max.x > box[0] && wgsbox.max.x < box[2]) {
+                    matchedIds.push({
+                        url: itm.url,
+                        id: idx
+                    });
                     return;
                 }
             }
-            if(wgsbox.min.x < box[0] && wgsbox.max.x > box[2] && wgsbox.min.y > box[1] && wgsbox.max.y < box[3]) {
-                matchedIds.push({url: itm.url, id: idx});
+            if (wgsbox.min.x < box[0] && wgsbox.max.x > box[2] && wgsbox.min.y > box[1] && wgsbox.max.y < box[3]) {
+                matchedIds.push({
+                    url: itm.url,
+                    id: idx
+                });
                 return;
             }
         }
@@ -235,18 +270,18 @@
     updateSelectedFeatures: function(ids, append) {
         var self = this;
 
-        if(ids.length == 1 && !append && self.selectedFeatures.length == 0) {
+        if (ids.length == 1 && !append && self.selectedFeatures.length == 0) {
             $('li[title="' + ids[0].url + '"] li[idx="' + ids[0].id + '"]').click();
         } else {
-            if(!append) {
+            if (!append) {
                 self.selectedFeatures = [];
             }
             $.each(ids, function(_, v) {
                 var contained = false;
                 $.each(self.selectedFeatures, function(_, sel) {
-                    if(v.url == sel.url && v.id == sel.id) contained = true;
+                    if (v.url == sel.url && v.id == sel.id) contained = true;
                 });
-                if(!contained) {
+                if (!contained) {
                     self.selectedFeatures.push(v);
                 }
             });
@@ -259,15 +294,15 @@
 
             $('#selection-dialog').dialog('destroy').remove();
 
-            if(self.selectedFeatures.length == 0) {
+            if (self.selectedFeatures.length == 0) {
                 Mapbender.modules.digitize_widget.closeEditDialog();
             }
 
-            if(self.selectedFeatures.length > 1) {
+            if (self.selectedFeatures.length > 1) {
                 Mapbender.modules.digitize_widget.closeEditDialog();
                 var dlg = $(self.selectionDialog);
                 var list = dlg.find('#selected-features-list')
-                .html('');
+                    .html('');
                 $.each(self.selectedFeatures, function(_, v) {
                     var feat = self._kmls[v.url].data.features[v.id];
                     var title = feat.properties.name;
@@ -283,7 +318,10 @@
                     }
                 });
                 dlg.find('.digitize-export').bind('click', function() {
-                    var data = {type: 'FeatureCollection', features: []};
+                    var data = {
+                        type: 'FeatureCollection',
+                        features: []
+                    };
                     $.each(self.selectedFeatures, function(_, v) {
                         var feat = self._kmls[v.url].data.features[v.id];
                         data.features.push(feat);
@@ -292,10 +330,10 @@
                     dlg.dialog('close');
                 });
                 dlg.find('.digitize-remove').bind('click', function() {
-                    if(confirm('Do you really want to remove all these objects?')) {
+                    if (confirm('Do you really want to remove all these objects?')) {
                         var urls = [];
                         $.each(self.selectedFeatures, function(_, v) {
-                            if($.inArray(v.url, urls) == -1) {
+                            if ($.inArray(v.url, urls) == -1) {
                                 urls.push(v.url);
                             }
                             $('#kmlTree li[title="' + v.url + '"] li[idx="' + v.id + '"]').remove();
@@ -321,8 +359,14 @@
 
         var bbox = this.getBbox(item.data.features[idx]);
 
-        var min = Proj4js.transform(this.wgs84, this.targetProj, {x: bbox[0], y: bbox[1]});
-        var max = Proj4js.transform(this.wgs84, this.targetProj, {x: bbox[2], y: bbox[3]});
+        var min = Proj4js.transform(this.wgs84, this.targetProj, {
+            x: bbox[0],
+            y: bbox[1]
+        });
+        var max = Proj4js.transform(this.wgs84, this.targetProj, {
+            x: bbox[2],
+            y: bbox[3]
+        });
 
         map.calculateExtent(
             new Mapbender.Extent(min.x, min.y, max.x, max.y)
@@ -332,13 +376,19 @@
 
     zoomToLayer: function(url) {
         var bbox = this.getLayerBbox(url);
-        if(!bbox) {
+        if (!bbox) {
             return;
         }
         var map = $('#mapframe1').mapbender();
 
-        var min = Proj4js.transform(this.wgs84, this.targetProj, {x: bbox[0], y: bbox[1]});
-        var max = Proj4js.transform(this.wgs84, this.targetProj, {x: bbox[2], y: bbox[3]});
+        var min = Proj4js.transform(this.wgs84, this.targetProj, {
+            x: bbox[0],
+            y: bbox[1]
+        });
+        var max = Proj4js.transform(this.wgs84, this.targetProj, {
+            x: bbox[2],
+            y: bbox[3]
+        });
 
         map.calculateExtent(new Mapbender.Extent(min.x, min.y, max.x, max.y));
         map.zoom(true, 0.99999999);
@@ -369,7 +419,7 @@
 
         var geom = new Geometry();
         var multi = new MultiGeometry(tp);
-        for(var i = 0; i < pts.length; ++i) {
+        for (var i = 0; i < pts.length; ++i) {
             var pt = Proj4js.transform(this.targetProj, this.wgs84, pts[i].pos);
             geom.addPoint(pt);
         }
@@ -382,21 +432,27 @@
         multi.e.setElement('name', 'name');
         attributesDialog.find('table input').each(function() {
             var name = $(this).attr('name');
-            if(name) {
+            if (name) {
                 multi.e.setElement($(this).attr('name'), $(this).val());
             }
         });
 
-        if(icon == "false" || icon === false){
+        if (icon == "false" || icon === false) {
             multi.e.setElement("Mapbender:iconOffsetX", -10);
             multi.e.setElement("Mapbender:iconOffsetY", -34);
-            multi.e.setElement("Mapbender:icon","../img/marker/red.png");
+            multi.e.setElement("Mapbender:icon", "../img/marker/red.png");
         }
 
         var feat = JSON.parse(multi.toString());
         itm.data.features.push(feat);
 
-        this.element.trigger('kml:loaded',{type:"geojson",data:itm.data,url:itm.url,display: itm.display, refreshing: true});
+        this.element.trigger('kml:loaded', {
+            type: "geojson",
+            data: itm.data,
+            url: itm.url,
+            display: itm.display,
+            refreshing: true,
+        });
         $map.setMapRequest();
     },
 
@@ -404,55 +460,104 @@
         this.cache = {};
         var $map = $(this.element).mapbender();
         var itm = this._kmls[url];
-        if(!itm) {
+        if (!itm) {
             return;
         }
-        this.element.trigger('kml:loaded',{type:"geojson",data:itm.data,url:itm.url,display: itm.display, refreshing: true});
+        this.element.trigger('kml:loaded', {
+            type: "geojson",
+            data: itm.data,
+            url: itm.url,
+            display: itm.display,
+            refreshing: true
+        });
         $map.setMapRequest();
     },
 
-    _load: function(url){
-        var self = this, o = this.options;
+    _load: function(url) {
+        var self = this,
+            o = this.options;
         var epsg = $(self.element).mapbender().epsg;
         epsg = epsg.split(":")[1];
-        if(self._kmls[o.url]){
-            //not adding feed twice
+        if (self._kmls[o.url]) {
+            //not adding feed twiced
             return;
         }
 
         this.kmlOrder.push(o.url);
 
-        $.ajax({ url: '../php/kmlToGeoJSON.php',
-                 data: {url: o.url, targetEPSG: 'EPSG:4326'},
-                 type: 'POST',
-                 dataType: "json",
-                 success : function(data,textStatus,xhr){
-                     if(!data){
-                         self.element.trigger('kml:error',"request returned no data");
-                     }
-                     else if(data.errorMessage){
-                         self.element.trigger('kml:error',data.errorMessage);
-                     }else{
-                         self._kmls[o.url] = {type:"geojson",data:data,url:o.url,display: o.autoDisplay};
-                         self.zoomToLayer(o.url);
-                         self.element.trigger('kml:loaded',{type:"geojson",data:data,url:o.url,display: o.autoDisplay});
-                     }
-                 },
-                 error: function(XMLHttpRequest, textStatus, errorThrown){
-                     self.element.trigger('kml:error',"Problem talking to server: " + errorThrown);
-                 }
-               });
+        $.ajax({
+            url: '../php/kmlToGeoJSON.php',
+            data: {
+                url: o.url,
+                targetEPSG: 'EPSG:4326'
+            },
+            type: 'POST',
+            success: function(data, textStatus, xhr) {
+                var json_result;
+
+                if (!data) {
+                    console.log('test');
+                    self.element.trigger('kml:error', "request returned no data");
+                } else if (data.errorMessage) {
+
+                    self.element.trigger('kml:error', data.errorMessage);
+                } else {
+                    //listen to gpx files
+                    try {
+                        // console.log(data);
+                        json_string = JSON.parse(data);
+                        json_result = JSON.parse(data);
+                    } catch (e) {
+
+                        var xml = new DOMParser().parseFromString(data, 'application/xml');
+                        json_result = toGeoJSON.gpx(xml);
+                    }
+                    var kml = $('#mapframe1').data('kml');
+                    var name;
+                    if (json_result.hasOwnProperty('@context')) {
+
+                        name = json_result['@context']['title'];
+                        kml.addLayer(name, json_result);
+                    } else {
+
+                        name = o.url;
+                        if (name.match(/\w*\W(?:kml|gpx|geojson)$/)) {
+                            name = name.match(/\w*\W(?:kml|gpx|geojson)$/)[0];
+                        }else {
+
+                            name = 'ImportFeatures';
+                        }
+                        kml.addLayer(name, json_result);
+                    }
+                }
+            },
+            error: function(XMLHttpRequest, textStatus, errorThrown) {
+
+
+                self.element.trigger('kml:error', "Problem talking to server: " + errorThrown);
+            }
+        });
     },
 
     addLayer: function(url, data) {
-        if($.inArray(url, this.kmlOrder) !== -1) {
+        if ($.inArray(url, this.kmlOrder) !== -1) {
             alert('Not adding ' + url + ', a layer with that name is already loaded.');
             return;
         }
         this.kmlOrder.push(url);
-        this._kmls[url] = {type:"geojson",data:data,url:url,display: true};
+        this._kmls[url] = {
+            type: "geojson",
+            data: data,
+            url: url,
+            display: true
+        };
         this.zoomToLayer(url);
-        this.element.trigger('kml:loaded',{type:"geojson",data:data,url:url,display: true});
+        this.element.trigger('kml:loaded', {
+            type: "geojson",
+            data: data,
+            url: url,
+            display: true
+        });
     },
 
     setOrder: function(order) {
@@ -472,7 +577,7 @@
         $map.setMapRequest();
     },
 
-    show : function(url){
+    show: function(url) {
         this._kmls[url].display = true;
         var $map = $(this.element).mapbender();
         var extent = $map.getExtentInfos();
@@ -481,7 +586,7 @@
         $(this.element).mapbender().setMapRequest();
     },
 
-    hide : function(url){
+    hide: function(url) {
         this._kmls[url].display = false;
         var $map = $(this.element).mapbender();
         var extent = $map.getExtentInfos();
@@ -489,7 +594,7 @@
         $map.setMapRequest();
     },
 
-    remove: function(url){
+    remove: function(url) {
         delete this._kmls[url];
         this.kmlOrder.splice(this.kmlOrder.indexOf(url), 1);
         delete this.cache[url];
@@ -502,7 +607,7 @@
     getLayerBbox: function(url) {
         var self = this;
         var itm = this._kmls[url];
-        if(itm.data.features.length == 0) {
+        if (itm.data.features.length == 0) {
             return false;
         }
         var bbox = this.getBbox(itm.data.features[0]);
@@ -517,75 +622,78 @@
     },
 
     getBbox: function(feature) {
-        switch(feature.geometry.type.toLowerCase()) {
+        switch (feature.geometry.type.toLowerCase()) {
             case 'point':
-            var map = $(this.element).mapbender();
-            var minx = feature.geometry.coordinates[0] - 0.001;
-            var miny = feature.geometry.coordinates[1] - 0.001;
-            return [minx, miny, minx + 0.002, miny + 0.002];
+                var map = $(this.element).mapbender();
+                var minx = feature.geometry.coordinates[0] - 0.001;
+                var miny = feature.geometry.coordinates[1] - 0.001;
+                return [minx, miny, minx + 0.002, miny + 0.002];
 
             case 'linestring':
-            var coords = feature.geometry.coordinates;
-            minx = coords[0][0];
-            miny = coords[0][1];
-            var maxx = minx;
-            var maxy = miny;
-            $.each(coords, function(_, v) {
-                minx = Math.min(minx, v[0]);
-                miny = Math.min(miny, v[1]);
-                maxx = Math.max(maxx, v[0]);
-                maxy = Math.max(maxy, v[1]);
-            });
-            return [minx, miny, maxx, maxy];
+                var coords = feature.geometry.coordinates;
+                minx = coords[0][0];
+                miny = coords[0][1];
+                var maxx = minx;
+                var maxy = miny;
+                $.each(coords, function(_, v) {
+                    minx = Math.min(minx, v[0]);
+                    miny = Math.min(miny, v[1]);
+                    maxx = Math.max(maxx, v[0]);
+                    maxy = Math.max(maxy, v[1]);
+                });
+                return [minx, miny, maxx, maxy];
 
             case 'polygon':
-            coords = feature.geometry.coordinates;
-            minx = coords[0][0][0];
-            miny = coords[0][0][1];
-            maxx = minx;
-            maxy = miny;
-            $.each(coords, function(_, v) {
-                $.each(v, function(_, v2) {
-                    minx = Math.min(minx, v2[0]);
-                    miny = Math.min(miny, v2[1]);
-                    maxx = Math.max(maxx, v2[0]);
-                    maxy = Math.max(maxy, v2[1]);
+                coords = feature.geometry.coordinates;
+                minx = coords[0][0][0];
+                miny = coords[0][0][1];
+                maxx = minx;
+                maxy = miny;
+                $.each(coords, function(_, v) {
+                    $.each(v, function(_, v2) {
+                        minx = Math.min(minx, v2[0]);
+                        miny = Math.min(miny, v2[1]);
+                        maxx = Math.max(maxx, v2[0]);
+                        maxy = Math.max(maxy, v2[1]);
+                    });
                 });
-            });
-            return [minx, miny, maxx, maxy];
+                return [minx, miny, maxx, maxy];
         }
         return undefined;
     },
 
     renderPoint: function(canvas, feature) {
-        var pt = {x: feature.geometry.coordinates[0],
-                  y: feature.geometry.coordinates[1]};
-        if(isNaN(pt.x) || isNaN(pt.y)) return;
-        if(!feature.preview) {
+        var pt = {
+            x: feature.geometry.coordinates[0],
+            y: feature.geometry.coordinates[1]
+        };
+        if (isNaN(pt.x) || isNaN(pt.y)) return;
+        if (!feature.preview) {
             pt = $('#mapframe1').mapbender().convertRealToPixel(pt);
         }
-        if(isNaN(pt.x) || isNaN(pt.y)) return;
+        if (isNaN(pt.x) || isNaN(pt.y)) return;
         // is this the right place and way to fix it?
-        if(feature.properties['Mapbender:icon']) {
+        if (feature.properties['Mapbender:icon']) {
             feature.properties['marker-symbol'] = feature.properties['Mapbender:icon'];
             feature.properties['marker-type'] = 'custom';
             feature.properties['Mapbender:icon'] = null;
         }
-        if(feature.properties['Mapbender:iconOffsetX']) {
+        if (feature.properties['Mapbender:iconOffsetX']) {
             feature.properties['marker-offset-x'] = feature.properties['Mapbender:iconOffsetX'];
             feature.properties['Mapbender:iconOffsetX'] = null;
         }
-        if(feature.properties['Mapbender:iconOffsetY']) {
+        if (feature.properties['Mapbender:iconOffsetY']) {
             feature.properties['marker-offset-y'] = feature.properties['Mapbender:iconOffsetY'];
             feature.properties['Mapbender:iconOffsetY'] = null;
         }
-        if(feature.properties['marker-type'] === 'custom') {
+        if (feature.properties['marker-type'] === 'custom') {
             var size = 32;
-            if(feature.properties['marker-size']) {
+            if (feature.properties['marker-size']) {
                 size = feature.properties['marker-size'];
             }
-            var offx = 0, offy = 0;
-            if(feature.preview) {
+            var offx = 0,
+                offy = 0;
+            if (feature.preview) {
                 size = 20;
             } else {
                 offx = feature.properties['marker-offset-x'] || 0;
@@ -594,32 +702,32 @@
                 offy = parseInt(offy);
             }
             var img = canvas.image(feature.properties['marker-symbol'], pt.x + offx, pt.y + offy, size, size).node;
-            if(img.setAttributeNS) {
-                img.setAttributeNS(null, "preserveAspectRatio" , "xMidYMid meet" );
+            if (img.setAttributeNS) {
+                img.setAttributeNS(null, "preserveAspectRatio", "xMidYMid meet");
             }
         } else {
             var size = 32;
-            if(feature.properties['marker-size']) {
-                if(feature.properties['marker-size'] === 'large') {
+            if (feature.properties['marker-size']) {
+                if (feature.properties['marker-size'] === 'large') {
                     size = 64;
                 }
-                if(feature.properties['marker-size'] === 'small') {
+                if (feature.properties['marker-size'] === 'small') {
                     size = 16;
                 }
             }
-            if(feature.preview) {
+            if (feature.preview) {
                 size = 20;
             }
 
-            if(!this.icons) {
-                window.setTimeout($.proxy(function(){
+            if (!this.icons) {
+                window.setTimeout($.proxy(function() {
                     this.renderPoint(canvas, feature);
                 }, this), 100);
                 return;
             }
 
             $.each(this.icons.icons, function(_, v) {
-                if(v.properties.name === (feature.properties['marker-symbol'] + '-24')) {
+                if (v.properties.name === (feature.properties['marker-symbol'] + '-24')) {
                     $.each(v.icon.paths, function(_, p) {
                         var raph = Raphael();
                         var tmp = raph.path(p);
@@ -629,19 +737,19 @@
                         var path = canvas.path(p);
 
                         var fac;
-                        if(box.width > box.height) {
+                        if (box.width > box.height) {
                             fac = size / box.width;
                         } else {
                             fac = size / box.height;
                         }
 
-                        if(feature.preview) {
+                        if (feature.preview) {
                             fac = fac * 0.7;
                         }
 
                         // center icon on 0/0, then scale to size, then translate to actual point
                         // for preview, just start at 0/0
-                        if(feature.preview) {
+                        if (feature.preview) {
                             path.translate(-box.x, -box.y);
                         } else {
                             path.translate(-box.x - box.width / 2, -box.y - box.height / 2);
@@ -649,7 +757,7 @@
                         // if you get a chrome error 'Invalid value for <path> attribute transform="  "' see:
                         // http://forum.wakanda.org/showthread.php?6753-error-raphael-min.js-7&p=31624&viewfull=1
                         path.scale(fac, fac, 0, 0);
-                        if(!feature.preview) {
+                        if (!feature.preview) {
                             path.translate(pt.x, pt.y);
                         }
 
@@ -666,12 +774,15 @@
         var self = this;
         var path;
         $.each(feature.geometry.coordinates, function(_, v) {
-            var pt = {x: v[0], y: v[1]};
-            if(!feature.preview) {
+            var pt = {
+                x: v[0],
+                y: v[1]
+            };
+            if (!feature.preview) {
                 pt = map.convertRealToPixel(pt);
             }
-            if(isNaN(pt.x) || isNaN(pt.y)) return;
-            if(!path) {
+            if (isNaN(pt.x) || isNaN(pt.y)) return;
+            if (!path) {
                 path = 'M' + pt.x + ' ' + pt.y;
             } else {
                 path += 'L' + pt.x + ' ' + pt.y;
@@ -686,12 +797,15 @@
         var self = this;
         var path;
         $.each(feature.geometry.coordinates[0], function(_, v) {
-            var pt = {x: v[0], y: v[1]};
-            if(!feature.preview) {
+            var pt = {
+                x: v[0],
+                y: v[1]
+            };
+            if (!feature.preview) {
                 pt = map.convertRealToPixel(pt);
             }
-            if(isNaN(pt.x) || isNaN(pt.y)) return;
-            if(!path) {
+            if (isNaN(pt.x) || isNaN(pt.y)) return;
+            if (!path) {
                 path = 'M' + pt.x + ' ' + pt.y;
             } else {
                 path += 'L' + pt.x + ' ' + pt.y;
@@ -703,22 +817,22 @@
     renderFeature: function(canvas) {
         var self = this;
         return function(_, feature) {
-            try{
-                if(feature.display === false) {
+            try {
+                if (feature.display === false) {
                     return;
                 }
-                switch(feature.geometry.type.toLowerCase()) {
+                switch (feature.geometry.type.toLowerCase()) {
                     case 'point':
-                    self.renderPoint(canvas, feature);
-                    break;
+                        self.renderPoint(canvas, feature);
+                        break;
                     case 'linestring':
-                    self.renderLine(canvas, feature);
-                    break;
+                        self.renderLine(canvas, feature);
+                        break;
                     case 'polygon':
-                    self.renderPolygon(canvas, feature);
-                    break;
+                        self.renderPolygon(canvas, feature);
+                        break;
                 };
-            }catch(e) {
+            } catch (e) {
                 console && console.log('Problem rendering feature', feature, e)
             }
         }
@@ -726,7 +840,7 @@
 
     renderPreview: function(feature, target, size) {
         var canvas;
-        if(size) {
+        if (size) {
             canvas = Raphael(target, size, size);
         } else {
             canvas = Raphael(target, 20, 20);
@@ -743,30 +857,40 @@
 
         var min = size / 8;
         var max = size - size / 8;
-        switch(feature.geometry.type.toLowerCase()) {
+        switch (feature.geometry.type.toLowerCase()) {
             case 'point':
-            feat.geometry.coordinates = [0, 0];
-            break;
+                feat.geometry.coordinates = [0, 0];
+                break;
             case 'linestring':
-            feat.geometry.coordinates = [[min, max], [max, min]];
-            break;
+                feat.geometry.coordinates = [
+                    [min, max],
+                    [max, min]
+                ];
+                break;
             case 'polygon':
-            feat.geometry.coordinates = [[[min, min], [min, max], [max, max], [max, min]]];
-            break;
+                feat.geometry.coordinates = [
+                    [
+                        [min, min],
+                        [min, max],
+                        [max, max],
+                        [max, min]
+                    ]
+                ];
+                break;
         };
 
         this.renderFeature(canvas)(null, feat);
     },
 
     render: function() {
-        if(this.creatingPhase) {
+        if (this.creatingPhase) {
             return;
         }
         var target = $('#kml-rendering-pane');
         var map = $('#mapframe1').mapbender();
         this.targetProj = new Proj4js.Proj(map.getSrs());
         var self = this;
-        if(target.length == 0) {
+        if (target.length == 0) {
             $('#mapframe1').append('<div id="kml-rendering-pane" style="position: absolute; top: 0px; left: 0px; z-index: 80;"></div>');
         }
         target = $('#kml-rendering-pane').html('').get(0);
@@ -777,18 +901,18 @@
 
         $.each(order, function(_, url) {
             var item = self._kmls[url];
-            if(!item) {
+            if (!item) {
                 return;
             }
             var feats = item.data.features;
 
-            if(!map.getSrs().match(/:4326/)) {
-                if(!self.cache[url]) {
+            if (!map.getSrs().match(/:4326/)) {
+                if (!self.cache[url]) {
                     self.cache[url] = {};
                 }
 
                 feats = self.cache[url][map.getSrs()];
-                if(!feats) {
+                if (!feats) {
                     $.each(item.data.features, function(_, v) {
                         self.fixupFeature(v);
                     });
@@ -797,7 +921,7 @@
                         type: 'POST',
                         data: JSON.stringify(item.data.features),
                         success: function(data) {
-                            if(!$.isArray(data)) {
+                            if (!$.isArray(data)) {
                                 data = JSON.parse(data);
                             }
                             self.cache[url][map.getSrs()] = data;
@@ -808,38 +932,37 @@
                 }
             }
 
-            if(item.display && feats) {
+            if (item.display && feats) {
                 $.each(feats, $.proxy(self, self.renderFeature(canvas)));
             }
         });
     },
 
     fixupFeature: function(feat) {
-        if(feat.geometry.type === 'Polygon') {
+        if (feat.geometry.type === 'Polygon') {
             $.each(feat.geometry.coordinates, function(_, coords) {
-                if(coords[0][0] !== coords[coords.length-1][0]
-                 || coords[0][1] !== coords[coords.length-1][1]) {
+                if (coords[0][0] !== coords[coords.length - 1][0] || coords[0][1] !== coords[coords.length - 1][1]) {
                     coords.push(coords[0]);
                 }
             });
         }
 
-        if(!feat.properties.uuid) {
+        if (!feat.properties.uuid) {
             feat.properties.uuid = UUID.genV1().toString();
         }
-        if(!feat.properties.updated) {
+        if (!feat.properties.updated) {
             feat.properties.updated = new Date().toISOString();
         }
-        if(!feat.properties.created) {
+        if (!feat.properties.created) {
             feat.properties.created = new Date().toISOString();
         }
     }
 
 };
 
-var displayKML = $.extend({},displayFeatures, {
+var displayKML = $.extend({}, displayFeatures, {
     _endpointURL: "../php/kml2transformedgeojson.php",
-    _eventNamespace : "kml"
+    _eventNamespace: "kml"
 });
-$.widget('ui.kml',displayKML);
-$.widget('ui.geojson',displayKML);
+$.widget('ui.kml', displayKML);
+$.widget('ui.geojson', displayKML);



More information about the Mapbender_commits mailing list