/*
 * JAVASCRIPT DEL COMPORTAMIENTO DEL MAPA
 */

		//Mapa
		var map;
		//Marker origen
		var origen=null;
		//Marker destino
		var destino=null;
		// Array de markers para múltiples puntos
		var arrayMarkers=[];
		// Variable que contiene la distancia total de la ruta
		var distance = null;
		// Variable que contiene la distancia de ida (sólo para el modo IDA_VUELTA)
		var distanceIda = null;
		// Variable que contiene la distancia de vuelta (sólo para el modo IDA_VUELTA)
		var distanceVuelta = null;
		// Elemento para mostrar las direcciones
		var directionsDisplay;
		// Elemento que contiene el polyline en case de no emplear direcciones
		var polyLine;		
		// Coordenadas del click
		var click_latLng=null;
		//DOM del mapa
		var DOM_mapa = document.getElementById("map_canvas");
		//DOM de context_menu
		var DOM_context_menu = document.getElementById("context_menu_A");
		// Servicio para calcular las direcciones
		var directionsService = new google.maps.DirectionsService();
		// Geocoder para la busqueda de direcciones
		var geocoder;
		// Constantes relativas al modo de ruta
		var INICIO_FIN = "inicioFin";
		var IDA_VUELTA = "idaVuelta";
		var MULTIPLES_PUNTOS = "multiples_puntos";
		var ID_INFORMADO = "id_informado";
		var RUTA_GPX = "ruta_gpx";
		// Variable que contiene el modo de tipo de ruta
		var tipoDeRuta = INICIO_FIN;
		// Constantes de rutas de imagenes
		var MARKER_INICIO = "./recursos/start.png";
		var MARKER_FIN = "./recursos/end.png";
		var MARKER_INICIO_FIN = "./recursos/start_end.png";
		var MARKER_MITAD = "./recursos/mitad.png";
		var MARKER_PUEBLO = "./recursos/punto.png";
		// Variable que contiene la ruta a la imagen del primer marcador
		var iconFirstMarker = MARKER_INICIO;
		// Variable que contiene la ruta a la imagen del segundo marcador
		var iconSecondMarker = MARKER_FIN;
		// Variable que controla si la ruta sigue los caminos o no
		var seguirCaminos = true;
		// Array de markers de pueblos
		var arrayMarkersPueblos = [];
		// Tipo de caminos
		var myTravelMode = google.maps.DirectionsTravelMode.WALKING;
		// Variables empleadas para Google Earth
		var ge;
		var earth_mode = false; 
		// Load Google Earth
		google.load("earth", "1.x");
		// Polylinea en Earth
		var lineStringPlacemark;
		// KML que contiene el tour
		var kmlObject;
		var earth_origen;
		var earth_destino;

/*
 * Inicializacion de google map
 */
function initializeMap() {
		//Se intenta obtener la localización, sino se centra sobre España
		var myLatlng = new google.maps.LatLng(40.38839687388361, -3.680419921875);
		// Try W3C Geolocation method
		if(navigator.geolocation) {
		   navigator.geolocation.getCurrentPosition(function(position) {
			   myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			   map.setCenter(myLatlng);
		   });
		} 		 		
		
 		// Creacion del mapa
		var myOptions = {
			streetViewControl: false,
			overviewMapControl: false,
		    mapTypeControlOptions: {
		        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
		    },
			zoom: 9,
			center: myLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(DOM_mapa, myOptions);

		// Muestra menu de contexto al hacer click derecho
		google.maps.event.addListener(map, 'rightclick', function(clk) {
			// No se muestra el menu si la ruta es de tipo guardad
			if (tipoDeRuta != ID_INFORMADO){
		        var x=clk.pixel.x;
		        var y=clk.pixel.y;
		        click_latLng = clk.latLng;
		        if (x > DOM_mapa.offsetWidth - DOM_context_menu.offsetWidth) { x = DOM_mapa.offsetWidth -  DOM_context_menu.offsetWidth; }
		        if (y > DOM_mapa.offsetHeight - DOM_context_menu.offsetHeight) { y = DOM_mapa.offsetHeight - DOM_context_menu.offsetHeight; }
		        DOM_context_menu.style.top= (DOM_mapa.offsetTop + y) + "px";
		        DOM_context_menu.style.left= (DOM_mapa.offsetLeft + x) + "px";
		        DOM_context_menu.style.visibility="visible";		
			}
		});	

	    // Si se realiza click fuera del menú contextual, se borra el menu
	    google.maps.event.addListener(map, "click", function() {
	    	DOM_context_menu.style.visibility="hidden";
	    });
	    
	    // Se inicializa el geocoder para busqueda de direcciones
	    geocoder = new google.maps.Geocoder();
	    
	    // Situa los botones en la parte superior del mapa
	    map.controls[google.maps.ControlPosition.TOP].push(document.getElementById("botones_mapa"));
}

/*
 * Función que centra el mapa en función a un nombre dado
 */
function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    });
}

/*
 * Función que establece el origen de la ruta
 */
function setOrigen(){
	if (origen != null){
		origen.setMap(null);
		origen=null;
	}
	origen = dibujaMarker(click_latLng, iconFirstMarker);
	if(destino != null){
		redibujaRuta();
	}	
}

/*
 * Función que establece el destino de la ruta
 */
function setDestino(){
	if (destino != null){
		destino.setMap(null);
		destino=null;
	}
	destino = dibujaMarker(click_latLng, iconSecondMarker);
	if(origen != null){
		redibujaRuta();
	}	
}

/*
 * Función que establece un punto en modo múltiples
 */
function establecePunto(){
	aniadePuntoMultiple(click_latLng);
	if(arrayMarkers.length > 1){
		redibujaRuta();
	}	
}

/*
 * Función que añade un punto múltiple al array
 */
function aniadePuntoMultiple (myLatLng){
	var iconMultiple = "./recursos/markers/marker"+arrayMarkers.length+".png";
	arrayMarkers.push(dibujaMarker(myLatLng, iconMultiple));
}

/*
 * Función que dibuja un marker y borra el menú contextual
 */
function dibujaMarker(myLatLng, myImage, draggable){
	  if (draggable === undefined ){
		  draggable = true;
	  }
      var marker = new google.maps.Marker({
        map:map,
        draggable:draggable,
        animation: false,
        position: myLatLng,
        icon: myImage
      });
      if (draggable){
    	  google.maps.event.addListener(marker, "dragend", function() {
    		  redibujaRuta();
    	  });  	  
      }
      DOM_context_menu.style.visibility="hidden";
      return marker;
}

/*
 * Función que redibuja la ruta cuando los markers son cambiados
 */
function redibujaRuta(){
	// No se redibuja si no se cumplen unos puntos mínimos
	if ((tipoDeRuta != MULTIPLES_PUNTOS && (origen==null || destino == null)) || 
		(tipoDeRuta == MULTIPLES_PUNTOS && arrayMarkers.length < 2)){
		return;
	}
    // Borra las rutas anteriores y los markers de pueblos
	borraMarkersPueblos();
	borraRutas();
	
	// Se borran los anteriores datos de perfil
	muestraDatosPerfil(false);
	
	// Si se siguen los caminos se pregunta por la mejor ruta para llegar desde el punto de inicio al punto de fin
	if(seguirCaminos){
		// Establece direcciones
	    directionsDisplay = new google.maps.DirectionsRenderer({
	        'map': map,
	        'preserveViewport': false,
	        'draggable': true,
	        'suppressMarkers': true 
	    });	
	    
	    // Se establece un listener
	    google.maps.event.addListener(directionsDisplay, 'directions_changed', function() { 
	        switch (tipoDeRuta) {
				case INICIO_FIN:
					distance = directionsDisplay.getDirections().routes[0].legs[0].distance.value;
					break;
				case IDA_VUELTA:
					distanceIda = directionsDisplay.getDirections().routes[0].legs[0].distance.value;
					distanceVuelta = directionsDisplay.getDirections().routes[0].legs[1].distance.value;
					distance = distanceIda + distanceVuelta;
					break;
				case MULTIPLES_PUNTOS:
					distance = directionsDisplay.getDirections().routes[0].legs[0].distance.value;
					break;
				default:
					break;
	        }
	    	borraMarkersPueblos();
	        muestraDistancia(true);	
	        muestraDatosPerfil(false);
	        estado_ruta = DISTANCIA_OBTENIDA;
	    });
	    
		// Se realiza un request para obtener la nueva dirección
		var request;
		
		// Las opciones de request dependen del tipo de ruta
		switch (tipoDeRuta) {
			case INICIO_FIN:
				request = {
					origin: origen.getPosition(),
				    destination: destino.getPosition(),	 	
				    travelMode: myTravelMode
				};
				break;
				
			case IDA_VUELTA:
				request = {
					origin: origen.getPosition(),
				    destination: origen.getPosition(),
				    waypoints:[{
			            location:  destino.getPosition(),
			            stopover:  true
			        }],	
				    travelMode: myTravelMode
				};		
				break;
				
			case MULTIPLES_PUNTOS:
				var myWayPoints = [];
				for ( var int = 1; int < arrayMarkers.length-1; int++) {
					myWayPoints.push({
						location:arrayMarkers[int].getPosition(),
						stopover: false
					});
				}
				request = {
						origin: arrayMarkers[0].getPosition(),
					    destination: arrayMarkers[arrayMarkers.length-1].getPosition(),
					    waypoints: myWayPoints,	
					    travelMode: myTravelMode
					};	
				break;
			default:
				break;
		}

	    directionsService.route(request, function(response, status) {
	      if (status == google.maps.DirectionsStatus.OK) {
	        directionsDisplay.setDirections(response);
	        // Se recoge la distancia de la ruta y se muestra
	        // en el caso de ida vuelta, hay distanciass totales y parciales
	        switch (tipoDeRuta) {
				case INICIO_FIN:
					distance = directionsDisplay.getDirections().routes[0].legs[0].distance.value;
					break;
				case IDA_VUELTA:
					distanceIda = directionsDisplay.getDirections().routes[0].legs[0].distance.value;
					distanceVuelta = directionsDisplay.getDirections().routes[0].legs[1].distance.value;
					distance = distanceIda + distanceVuelta;
					break;
				case MULTIPLES_PUNTOS:
					distance = directionsDisplay.getDirections().routes[0].legs[0].distance.value;
					break;					
				default:
					break;
			}
	        
	        muestraDistancia(true);
	      }
	    });	    
	// Si no se siguen los caminos, se dibuja una línea entre el punto de inicio y el de fin
	}else{
		var myPath=[];
		// Los puntos de ruta dependen del tipo de ruta y la distancia también
		switch (tipoDeRuta) {
			case INICIO_FIN:
				myPath = [origen.getPosition(),destino.getPosition()];
				distance = google.maps.geometry.spherical.computeDistanceBetween(origen.getPosition(),destino.getPosition());
				break;
				
			case IDA_VUELTA:
				myPath = [origen.getPosition(),destino.getPosition(),origen.getPosition()];		
				distanceIda = google.maps.geometry.spherical.computeDistanceBetween(origen.getPosition(),destino.getPosition());
				distanceVuelta = distanceIda;
				distance = distanceIda + distanceVuelta;
				break;
				
			case MULTIPLES_PUNTOS:
				distance = 0;
				for ( var int2 = 0; int2 < arrayMarkers.length; int2++) {
					myPath.push(arrayMarkers[int2].getPosition());
					if (int2 > 0){
						distance += google.maps.geometry.spherical.computeDistanceBetween(arrayMarkers[int2 - 1].getPosition(),arrayMarkers[int2].getPosition());		
					}
				}
				break;
				
			default:
				break;
		}
		polyLine = new google.maps.Polyline({
		      path:myPath,
		      strokeColor: "#0202FF",
		      strokeOpacity: 0.5,
		      strokeWeight: 4
		  	});
		polyLine.setMap(map);

        muestraDistancia(true);
	}
	estado_ruta = DISTANCIA_OBTENIDA;
}

// Función que establece el tipo de ruta en función del radio button seleccionado
function establecerTipoRuta (){
	switch (document.getElementById("tipo_ruta").selectedIndex) {
		case 0:
			// Inicio y fin
			tipoDeRuta = INICIO_FIN;
			// Se cambian los markers
			iconFirstMarker = MARKER_INICIO;
			iconSecondMarker = MARKER_FIN;	
			// Se establece el context menu
			setContextMenu("context_menu_A");
			// Si había puntos múltiples, se transforman los markers
			if (arrayMarkers.length > 0){
				origen = dibujaMarker(arrayMarkers[0].getPosition(), iconFirstMarker);
				if (arrayMarkers.length > 1){
					destino = dibujaMarker(arrayMarkers[arrayMarkers.length - 1].getPosition(), iconSecondMarker);
				}
				while (arrayMarkers.length > 0){
					arrayMarkers.pop().setMap(null);
				}
			}
			break;
		case 1:
			// Ida y vuelta	
			tipoDeRuta = IDA_VUELTA;
			// Se cambian los markers
			iconFirstMarker = MARKER_INICIO_FIN;
			iconSecondMarker = MARKER_MITAD;
			// Se establece el context menu
			setContextMenu("context_menu_A");
			// Si había puntos múltiples, se transforman los markers
			if (arrayMarkers.length > 0){
				origen = dibujaMarker(arrayMarkers[0].getPosition(), iconFirstMarker);
				if (arrayMarkers.length > 1){
					destino = dibujaMarker(arrayMarkers[arrayMarkers.length - 1].getPosition(), iconSecondMarker);
				}
				while (arrayMarkers.length > 0){
					arrayMarkers.pop().setMap(null);
				}
			}
			break;
		case 2:
			// Múltiples puntos	
			tipoDeRuta = MULTIPLES_PUNTOS;
			// Se establece el context menu
			setContextMenu("context_menu_B");
			// Si había puntos inicio y fin se emplean como markers 0 y 1
			if (origen!=null){
				aniadePuntoMultiple(origen.getPosition());
				origen.setMap(null);
				origen = null;
			}
			if (destino!=null){
				aniadePuntoMultiple(destino.getPosition());
				destino.setMap(null);
				destino = null;
			}	
			break;		
		default:
			break;
	}
	// Se redibujan los markers por si la imagen de los mismos ha sido modificada	
	if (origen!=null){
		origen.setIcon(iconFirstMarker);
	}
	if (destino!=null){
		destino.setIcon(iconSecondMarker);
	}	
	
	redibujaRuta();	
}

/*
 * Función que establece el modo de seguir las carreteras o no
 */
function establecer_modo_carreteras(){
	switch (document.getElementById("seguir_caminos").selectedIndex) {
		// Caminos secundarios
		case 0:
			seguirCaminos = true;
			myTravelMode = google.maps.DirectionsTravelMode.WALKING;
			document.getElementById("mostrar_pueblos").disabled=false;
			break;
		// Caminos principales
		case 1:
			seguirCaminos = true;
			myTravelMode = google.maps.DirectionsTravelMode.DRIVING;
			document.getElementById("mostrar_pueblos").disabled=false;
			break;
		// No seguir caminos
		case 2:
			seguirCaminos = false;
			document.getElementById("mostrar_pueblos").disabled=true;
			break;
		default:
			break;
	}
	redibujaRuta();	
}

/*
 * Borra los elementos presentados en el mapa
 */

function borra_mapa(){
	borraMarkers();
	borraMarkersPueblos();
	borraRutas();
}

function borraMarkers(){
	if (origen!=null){
		origen.setMap(null);
	}
	if (destino!=null){
		destino.setMap(null);
	}
	origen=null;
	destino=null;
	while (arrayMarkers.length > 0){
		arrayMarkers.pop().setMap(null);
	}	
}

function borraMarkersPueblos(){
	while (arrayMarkersPueblos.length > 0){
		arrayMarkersPueblos.pop().setMap(null);
	}	
}

function borraRutas(){
	if (directionsDisplay!=null){
		directionsDisplay.setMap(null);
		directionsDisplay = null;
	}	
	if (polyLine!=null){
		polyLine.setMap(null);
		polyLine = null;
	}	
}
/*
 * Se establece un context menu diferente atendiendo al modo de ruta
 * - Inicio fin, o ida y vuela: Context menu A
 * - Multiples puntos: Context menu B
 */
function setContextMenu(menu){
	DOM_context_menu = document.getElementById(menu);
}

/*
 * Añade marker de tipo pueblo 
 */
function addMarkerPueblo(myLatLng,info){
	// Se extrae el nombre para crear la ventana
    var infowindow = new google.maps.InfoWindow ({
    	content: info 
    });
    // Se centra el marker
    var myMarkerImage = new google.maps.MarkerImage(MARKER_PUEBLO, null, null, new google.maps.Point(12, 12));
    // Se situa un marker en las coordenadas
    var marker = new google.maps.Marker({
        position: myLatLng, 
        map: map,
        icon: myMarkerImage
    });
    // Se añade el marker al array de markers de pueblos
    arrayMarkersPueblos.push(marker);
    
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
    });
    return marker;
}

/*
 * Función que dibuja un camino sobre el mapa en base a los puntos guardados en la BBDD
 */
function dibujaCaminoGuardado (ptos){
	var myPath = [];
	
	// Bounds para centrar el mapa
	var bounds = new google.maps.LatLngBounds();
	
	// Se muestra el polyline asociado
	for ( var i in ptos) {
		var lat = 0;
		var lng = 0;
		for (var myValues in ptos[i].location){	
			if (lat == 0){
				lat = ptos[i].location[myValues];
			}else if (lng == 0){
				lng = ptos[i].location[myValues];
			}		
		}
		var myLatLng = new google.maps.LatLng(lat,lng);
		myPath.push(myLatLng);
		bounds.extend(myLatLng);
	}
	polyLine = new google.maps.Polyline({
	      path:myPath,
	      strokeColor: "#0202FF",
	      strokeOpacity: 0.5,
	      strokeWeight: 4
	  	});
	polyLine.setMap(map);
	map.fitBounds(bounds);
	
	// Se crean markers de inicio y fin
	origen = dibujaMarker(myPath[0],MARKER_INICIO,false);
	destino = dibujaMarker(myPath[myPath.length - 1],MARKER_FIN,false);
}
/*
 * Función que dibuja un camino sobre el mapa en base a los puntos de un fichero GPX
 */
function dibujaCaminoGPX (DOM_trkpts){
	var myPath = [];
	var bounds = new google.maps.LatLngBounds();
	
	for ( var i = 0; i < DOM_trkpts.length; i++) {
		var pto = DOM_trkpts[i];
		var myLatLng = new google.maps.LatLng(pto.getAttribute("lat"),pto.getAttribute("lon"));
		myPath.push(myLatLng);
		bounds.extend(myLatLng);		
	}
	polyLine = new google.maps.Polyline({
	      path:myPath,
	      strokeColor: "#0202FF",
	      strokeOpacity: 0.5,
	      strokeWeight: 4
	  	});
  	polyLine.setMap(map);
  	map.fitBounds(bounds);	

	// Se crean markers de inicio y fin
	origen = dibujaMarker(myPath[0],MARKER_INICIO,false);
	destino = dibujaMarker(myPath[myPath.length - 1],MARKER_FIN,false);
	
	ocultarOpciones(true);
}

/*
 * Función que obtiene la distancia de puntos GPX
 */
function obtieneDistanciaCaminoGuardado (DOM_trkpts){
	var distanceAux = 0;
	var myPreviousLatLng;	
	for ( var i = 0; i < DOM_trkpts.length; i++) {
		var pto = DOM_trkpts[i];
		var myLatLng = new google.maps.LatLng(pto.getAttribute("lat"),pto.getAttribute("lon"));
		if (i>0){
			distanceAux += google.maps.geometry.spherical.computeDistanceBetween(myPreviousLatLng,myLatLng);
		}	
		myPreviousLatLng = myLatLng;
	}
	return distanceAux;
}
  
/*
 * Función que cambia entre 2D y 3D
 */
function toggle_2D_3D() {
	if (estado_ruta == NUEVA_RUTA){
		return;
	}
	if (!earth_mode){
		if (!ge){
			google.earth.createInstance('earth_div', initializeEarth, failureEarth);
		}else{
			ge.getWindow().setVisibility(true);
			draw_earth_path();
		}		
		document.getElementById("map_canvas").style.visibility = "hidden";
		document.getElementById("earth_div").style.visibility = "visible";
		action_on_server("3D"); 
	}else{
		document.getElementById("earth_div").style.visibility = "hidden";
		document.getElementById("map_canvas").style.visibility = "visible";
		ge.getWindow().setVisibility(false);
	}
	earth_mode = !earth_mode;
	muestraDistancia(true);
	if (tipoDeRuta == ID_INFORMADO){
		ocultarOpciones(true);
	}else{
		ocultarOpciones(earth_mode);
	}	
}

function initializeEarth(instance) {
	ge = instance;
	ge.getWindow().setVisibility(true);
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);     
	ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	draw_earth_path();
}

function draw_earth_path(){
	// Obtiene el path dibujado
	var path = get_path();
	
	// Crea la polilnea en Earth
	if (lineStringPlacemark !== undefined){
		ge.getFeatures().removeChild(lineStringPlacemark);
	}
    lineStringPlacemark = ge.createPlacemark('');
    var lineString = ge.createLineString('');
    lineStringPlacemark.setGeometry(lineString);
    
    for ( var i = 0; i < path.length; i++) {
    	lineString.getCoordinates().pushLatLngAlt(path[i].lat(), path[i].lng(), 0);    	
    }
    // Create a style and set width and color of line.
    lineStringPlacemark.setStyleSelector(ge.createStyle(''));
    var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
    lineStyle.setWidth(5);
    lineStyle.getColor().set('99FF0202');  // aabbggrr format

    // Add the feature to Earth.
    ge.getFeatures().appendChild(lineStringPlacemark);
    
	// Añade markers de inicio y fin
    if (earth_origen !== undefined){
    	ge.getFeatures().removeChild(earth_origen);
    }     
    if (earth_destino !== undefined){
    	ge.getFeatures().removeChild(earth_destino);
    }
    earth_origen = ge.createPlacemark('');
    earth_destino = ge.createPlacemark('');

    // Define a custom icon.
    var icon1 = ge.createIcon('');
    icon1.setHref('http://www.perfilderuta.es/recursos/start.png');
    var style1 = ge.createStyle('');
    style1.getIconStyle().setIcon(icon1);
    style1.getIconStyle().setScale(4.0);
    earth_origen.setStyleSelector(style1);

    // Define a custom icon.
    var icon2 = ge.createIcon('');
    icon2.setHref('http://www.perfilderuta.es/recursos/end.png');
    var style2 = ge.createStyle('');
    style2.getIconStyle().setIcon(icon2);
    style2.getIconStyle().setScale(4.0);
    earth_destino.setStyleSelector(style2);
    
    // Set the placemark's location.  
    var point1 = ge.createPoint('');
    point1.setLatitude(path[0].lat());
    point1.setLongitude(path[0].lng());
    earth_origen.setGeometry(point1);

    var point2 = ge.createPoint('');
    point2.setLatitude(path[path.length - 1].lat());
    point2.setLongitude(path[path.length - 1].lng());
    earth_destino.setGeometry(point2);
    
    // Add the placemark to Earth.
    ge.getFeatures().appendChild(earth_origen);
    ge.getFeatures().appendChild(earth_destino);
    
	// Obtiene el KML de tour
	if (kmlObject !== undefined){
		ge.getFeatures().removeChild(kmlObject);
	}
	var kmlString =  get_tour_kml(path);
	kmlObject = ge.parseKml(kmlString);
	ge.getFeatures().appendChild(kmlObject);
    // Walk through the KML to find the tour object; assign to variable 'tour.'
    walkKmlDom(kmlObject, function() {
       if (this.getType() == 'KmlTour') {
          var tour = this;
          ge.getTourPlayer().setTour(tour);
          return false;
       }
    });	
   }

 function failureEarth(errorCode) {
 }
 
 /*
  * Función que devuelve el path, ya sea de polylines o de directions
  */
 function get_path(){
	var path;
	// Si el camino sigue la ruta los puntos provienen de las direcciones, de lo contrario provienen del polyline
	if (seguirCaminos && (tipoDeRuta != RUTA_GPX) && (tipoDeRuta != ID_INFORMADO)){
		path = directionsDisplay.getDirections().routes[0].overview_path;
	}else{
		path = polyLine.getPath().getArray();
	}
	return path;
}
/*
 * Función que obtiene el KML asociado a un tour a partir de un path
 */ 
function get_tour_kml(path){
	var segundosTotal;
	if (distance < 50000){
		segundosTotal = 60;
	}else if (distance < 75000){
		segundosTotal = 90;
	}else if (distance < 100000){
		segundosTotal = 120;
	}else{
		segundosTotal = 150;
	}
	var maxHeading = 5;
	var kml = '<?xml version="1.0" encoding="UTF-8"?>'+
	'<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">'+
	'<Document>'+
	'<gx:Tour>'+
	'<name>Visita guiada sin título</name>'+
	'<gx:Playlist>';
	;
	for ( var i = 0; i < path.length; i++) {
		var duracion = 0;
		var heading;
		if (i>0){
			var disPuntos = google.maps.geometry.spherical.computeDistanceBetween(path[i],path[i-1]);
			duracion = segundosTotal * (disPuntos / distance);
			var headingNew = google.maps.geometry.spherical.computeHeading(path[i-1],path[i]);
			if (heading < 0){
				heading = 360 + heading;
			}
			if (headingNew < 0){
				headingNew = 360 + headingNew;
			}
			if ((headingNew - heading) > maxHeading){
				if ((headingNew - heading) > 180){
					heading = heading - maxHeading;
				}else{
					heading = heading + maxHeading;
				}
			}else if((heading - headingNew) > maxHeading){
				if ((heading - headingNew) > 180){
					heading = heading + maxHeading;
				}else{
					heading = heading - maxHeading;
				}				
			}else {
				heading = headingNew;
			}
		}else{
			heading = google.maps.geometry.spherical.computeHeading(path[0],path[1]);
		}
		if (heading > 360){
			heading = heading - 360;
		}
		kml+='<gx:FlyTo>'+
				'<gx:duration>'+duracion+'</gx:duration>'+
				'<gx:flyToMode>smooth</gx:flyToMode>'+
				'<LookAt>'+
					'<longitude>'+path[i].lng()+'</longitude>'+
					'<latitude>'+path[i].lat()+'</latitude>'+
					'<altitude>0</altitude>'+
					'<heading>'+heading+'</heading>'+
					'<tilt>75</tilt>'+
					'<range>1000</range>'+
				'</LookAt>'+
			'</gx:FlyTo>';  	
	}
	
	kml+='</gx:Playlist>'+
	'</gx:Tour>'+
	'</Document>'+
	'</kml>';
	
	return kml;
}
