Load a map with geoxml using parseKmlString() and parse()

3.1k views Asked by At

OLD POST

How can I use parse and parseKmlString together?? I need show a map loading one KML file (I use parse(<kml_file>)) and two XML string (I use parseKmlString(<xml_string>)). How I use useTheData in afterParse property?? I don't know how I must manage this case. Can I use only one geoxml = new geoxml.parser() for three "layers"? How would I manage doc parameter in userTheData to get a "KML file layer" or "XML string layer"?

PD: Sorry for my english. It's very difficult to explain what I need.

MODIFIED POST

I draw a map dinamically with ASP. If I get 3 layers, a write 3 object (geoxml_1, geoxml_2 and geoxml_3). It would be only one object, and show and hidden layer 1 or layer2.... That is my problem. Really it works, but it isn't fine code. When I load de map, it show all layers, and in a few seconds, only show the first layer and hidden the others. I would like whow only the first layer, an when I click the others layers in my buttons inside the map, it would show and hide de layers. This is my code (sorry, its too large):

function muestraCapasMapa(){
    var objCapa = document.getElementById("capas_mapa");
    var objFlecha = document.getElementById("flecha");
    if (objCapa.className=="ocultar"){
        objCapa.className = "";
        objFlecha.className = "plegar";
    }else{
        objCapa.className = "ocultar";
        objFlecha.className = "";
    }
}

var infoWindow;
var map_1 = null;
var geoXml_1;
var bounds_1;
var blnKmlServicio_1;
var geoXml_2;
var bounds_2;
var blnKmlServicio_2;
var geoXml_3;
var bounds_3;
var blnKmlServicio_3;
var boundsTotal;
var SDLLayer;
var btnPulsado;

function useTheData_1(doc){
    var geoXmlDoc = doc[0];                
    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {


    var placemark = geoXmlDoc.placemarks[i];
        var bounds_parciales;

        if (placemark.polyline) {

        bounds_parciales = placemark.polyline.bounds;

                bounds_1.union(bounds_parciales);

        }

        if (placemark.polygon){
            bounds_parciales = placemark.polygon.bounds;

                bounds_1.union(bounds_parciales);

        }

        if (placemark.marker) {

        bounds_parciales = placemark.marker.getPosition();

                bounds_1.extend(bounds_parciales);

        }

    }   // END FOR     
}   //END FUNCTION

function useTheData_2(doc){
    var geoXmlDoc = doc[0];                
    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {


    var placemark = geoXmlDoc.placemarks[i];
        var bounds_parciales;

        if (placemark.polyline) {

        bounds_parciales = placemark.polyline.bounds;

                bounds_2.union(bounds_parciales);

        }

        if (placemark.polygon){
            bounds_parciales = placemark.polygon.bounds;

                bounds_2.union(bounds_parciales);

        }

        if (placemark.marker) {

        bounds_parciales = placemark.marker.getPosition();

                bounds_2.extend(bounds_parciales);

        }

    }   // END FOR     
}   //END FUNCTION

function useTheData_3(doc){
    var geoXmlDoc = doc[0];                
    for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {


    var placemark = geoXmlDoc.placemarks[i];
        var bounds_parciales;

        if (placemark.polyline) {

        bounds_parciales = placemark.polyline.bounds;

                bounds_3.union(bounds_parciales);

        }

        if (placemark.polygon){
            bounds_parciales = placemark.polygon.bounds;

                bounds_3.union(bounds_parciales);

        }

        if (placemark.marker) {

        bounds_parciales = placemark.marker.getPosition();

                bounds_3.extend(bounds_parciales);

        }

    }   // END FOR     
}   //END FUNCTION


function initialize_1() {
    infoWindow = new google.maps.InfoWindow();
    var infoWindows = [];

    function closeAllInfoWindows(infoW) {
        for (var i=0;i<infoWindows.length;i++) {
            if (infoWindows[i] != infoW){
                infoWindows[i].close();
            }
        }
    }   

    boundsTotal = new google.maps.LatLngBounds();
    bounds_1 = new google.maps.LatLngBounds();
    bounds_2 = new google.maps.LatLngBounds();
    bounds_3 = new google.maps.LatLngBounds();

    //Declaramos las variables que vamos a user
    var lat_1 = null;
    var lng_1 = null;

    var lngLatitud;
    var lngLongitud;
    var zoom;
    zoom=9;
    var latLng = new google.maps.LatLng(36.82907321372808, -4.46044921875);

    //Definimos algunas opciones del mapa a crear
    var myOptions = {
        center: latLng, //centro del mapa
        zoom: zoom,
        scrollwheel: false,
        styles: [{"featureType": "water","elementType": "geometry","stylers": [{    "visibility": "on"}, {    "color": "#A6DBD8"}]}, {"featureType": "landscape","elementType": "geometry.fill","stylers": [{"color": "#DEDDAC"}]}, {"featureType": "poi","elementType": "geometry.fill","stylers": [{"color": "#769E72"}]}, {"featureType": "poi","elementType": "labels.text.fill","stylers": [{"color": "#7B8758"}]}, {"featureType": "poi","elementType": "labels.text.stroke","stylers": [{"color": "#EBF4A4"}]}, {"featureType": "poi.park","elementType": "geometry","stylers": [{"visibility": "simplified"}, {"color": "#CFD978"}]}, {"featureType": "road","elementType": "geometry.fill","stylers": [{"visibility": "simplified"}]}, {"featureType": "road","elementType": "labels.text.fill","stylers": [{"color": "#5B5B3F"}]}, {"featureType": "road","elementType": "labels.text.stroke","stylers": [{"color": "#ABCE83"}]}, {"featureType": "road","elementType": "labels.icon","stylers": [{"visibility": "off"}]}, {"featureType": "road.local","elementType": "geometry","stylers": [{"color": "#A4C67D"}]}, {"featureType": "road.arterial","elementType": "geometry","stylers": [{"color": "#CFCBB4"}]}, {"featureType": "road.highway","elementType": "geometry","stylers": [{"color": "#B6B6B6"}]}, {"featureType": "transit","stylers": [{"visibility": "off"}]}, {"featureType": "administrative","elementType": "geometry.stroke","stylers": [{"visibility": "on"}, {"color": "#87ae79"}]}, {"featureType": "administrative","elementType": "geometry.fill","stylers": [{"color": "#7f2200"}, {"visibility": "off"}]}, {"featureType": "administrative","elementType": "labels.text.stroke","stylers": [{"color": "#ffffff"}, {"visibility": "on"}, {"weight": 4.1}]}, {"featureType": "administrative","elementType": "labels.text.fill","stylers": [{"color": "#495421"}]}, {"featureType": "administrative.neighborhood","elementType": "labels","stylers": [{"visibility": "off"}]}],
        mapTypeId: google.maps.MapTypeId.ROADMAP //tipo de mapa, carretera, híbrido,etc
    }; // Fin my options

    //creamos el mapa con las opciones anteriores y le pasamos el elemento div
    map_1 = new google.maps.Map(document.getElementById("map_canvas_1"), myOptions);
    geoXml_1 = new geoXML3.parser({
        map: map_1,
        infoWindowOptions: {maxWidth:350},
        singleInfoWindow: true,
        suppressInfoWindows: false,
        afterParse: parseoTerminado_1,
        zoom: false
    });                    

    function parseoTerminado_1(doc){ 
        useTheData_1(doc);                   
        setTimeout(function() {
            compruebaCapas_1();
            setTimeout(function() {
                chequearCapas();
            }, 0) 
            /*chequeo burbujas*/                            


                $.each(geoXml_1.docs[0].gpolylines, function(index) {                           
                    infoWindows.push(geoXml_1.docs[0].gpolylines[index].infoWindow);                                                                 
                    google.maps.event.addListener(geoXml_1.docs[0].gpolylines[index], 'click', function() {
                        closeAllInfoWindows(geoXml_1.docs[0].gpolylines[index].infoWindow); 
                    });
                });

                $.each(geoXml_1.docs[0].markers, function(index) {                           
                    infoWindows.push(geoXml_1.docs[0].markers[index].infoWindow);                                     
                    google.maps.event.addListener(geoXml_1.docs[0].markers[index], 'click', function() {
                        closeAllInfoWindows(geoXml_1.docs[0].markers[index].infoWindow); 
                    });                                    
                });
                //console.log(".>" + infoWindows);

            /***************/
        }, 500) 
    }                   
    blnKmlServicio_1 = true;
    geoXml_1.parse('<URL_GET_KML>');

    geoXml_2 = new geoXML3.parser({
        map: map_1,
        infoWindowOptions: {maxWidth:350},

            singleInfoWindow: true,

            suppressInfoWindows: false,

        afterParse: parseoTerminado_2,
        zoom: false
    });                    

    function parseoTerminado_2(doc){ 
        useTheData_2(doc);                   
        setTimeout(function() {
            compruebaCapas_2();
            setTimeout(function() {
                chequearCapas();
            }, 0) 
            /*chequeo burbujas*/                            


                $.each(geoXml_2.docs[0].gpolylines, function(index) {                           
                    infoWindows.push(geoXml_2.docs[0].gpolylines[index].infoWindow);                                                                 
                    google.maps.event.addListener(geoXml_2.docs[0].gpolylines[index], 'click', function() {
                        closeAllInfoWindows(geoXml_2.docs[0].gpolylines[index].infoWindow); 
                    });
                });

                $.each(geoXml_2.docs[0].markers, function(index) {                           
                    infoWindows.push(geoXml_2.docs[0].markers[index].infoWindow);                                     
                    google.maps.event.addListener(geoXml_2.docs[0].markers[index], 'click', function() {
                        closeAllInfoWindows(geoXml_2.docs[0].markers[index].infoWindow); 
                    });                                    
                });
                //console.log(".>" + infoWindows);

            /***************/
        }, 500) 
    }                

    blnKmlServicio_2 = false;
    geoXml_2.parseKmlString("<KML_STRING>");

    geoXml_3 = new geoXML3.parser({
        map: map_1,
        infoWindowOptions: {maxWidth:350},

            singleInfoWindow: true,

            suppressInfoWindows: false,

        afterParse: parseoTerminado_3,
        zoom: false
    });                    

    function parseoTerminado_3(doc){ 
        useTheData_3(doc);                   
        setTimeout(function() {
            compruebaCapas_3();
            setTimeout(function() {
                chequearCapas();
            }, 0) 
            /*chequeo burbujas*/                            


                $.each(geoXml_3.docs[0].gpolylines, function(index) {                           
                    infoWindows.push(geoXml_3.docs[0].gpolylines[index].infoWindow);                                                                 
                    google.maps.event.addListener(geoXml_3.docs[0].gpolylines[index], 'click', function() {
                        closeAllInfoWindows(geoXml_3.docs[0].gpolylines[index].infoWindow); 
                    });
                });

                $.each(geoXml_3.docs[0].markers, function(index) {                           
                    infoWindows.push(geoXml_3.docs[0].markers[index].infoWindow);                                     
                    google.maps.event.addListener(geoXml_3.docs[0].markers[index], 'click', function() {
                        closeAllInfoWindows(geoXml_3.docs[0].markers[index].infoWindow); 
                    });                                    
                });
                //console.log(".>" + infoWindows);

            /***************/
        }, 500) 
    }                

    blnKmlServicio_3 = false;
    geoXml_3.parseKmlString("<KML_STRING>");

    CrearBotones(map_1);

    function compruebaCapas_1(n){
        if (!blnKmlServicio_1){
            if (document.getElementById("Capa_1")){
                if (document.getElementById("Capa_1").checked){
                    geoXml_1.showDocument();
                    boundsTotal.union(bounds_1);
                }else{
                    geoXml_1.hideDocument();
                }
            }
        }
    }

    function compruebaCapas_2(n){
        if (!blnKmlServicio_2){
            if (document.getElementById("Capa_2")){
                if (document.getElementById("Capa_2").checked){
                    geoXml_2.showDocument();
                    boundsTotal.union(bounds_2);
                }else{
                    geoXml_2.hideDocument();
                }
            }
        }
    }

    function compruebaCapas_3(n){
        if (!blnKmlServicio_3){
            if (document.getElementById("Capa_3")){
                if (document.getElementById("Capa_3").checked){
                    geoXml_3.showDocument();
                    boundsTotal.union(bounds_3);
                }else{
                    geoXml_3.hideDocument();
                }
            }
        }
    }


        $("a#inline").fancybox({
            // RESIZE MAP WHEN TU CLICK A BUTTON
        });

}   //END initialize 


function CrearBotones(map) {
    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    var controlDiv = document.createElement('div');
    controlDiv.style.padding = '5px';

    // Creamos el DIV que contendrá al botón y asignamos los estilos
    var controlUI_1 = document.createElement('div');
    controlUI_1.id = 'btnZoom';
    controlUI_1.style.backgroundColor = 'white';
    controlUI_1.style.borderStyle = 'solid';
    controlUI_1.style.borderWidth = '1px 1px 0px 1px';
    controlUI_1.style.borderColor = 'rgb(178, 177, 138)';
    controlUI_1.style.borderRadius = '2px';
    controlUI_1.style.boxShadow = '0px 2px 4px -1px rgba(0, 0, 0, 0.3)';
    controlUI_1.style.marginTop = '0px';
    controlUI_1.style.marginRight = '5px';
    controlUI_1.style.marginBottom = '5px';
    controlUI_1.style.paddingRight = '4px';
    controlUI_1.style.paddingBottom = '0px';
    controlUI_1.style.paddingLeft = '4px';
    controlUI_1.style.cursor = 'pointer';
    controlUI_1.style.textAlign = 'center';
    controlUI_1.style.display = 'block';
    controlUI_1.title = 'Haz click aquí para ampliar el mapa a pantalla completa';
    controlDiv.appendChild(controlUI_1);
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlUI_1);

    // Creamos el DIV interno que tendrá la etiqueta y HTML del botón
    var controlText_1 = document.createElement('div');
    controlText_1.style.fontFamily = 'Roboto,Arial,sans-serif';
    controlText_1.style.fontSize = '11px';
    controlText_1.style.lineHeight = '14.5px';
    controlText_1.style.paddingTop = '2px';
    controlText_1.style.paddingLeft = '4px';
    controlText_1.style.paddingRight = '4px';
    controlText_1.innerHTML = '<a id="inline" href="#divMapaGlobal" class="icon icon-fullscreen" style="font-size:11px;text-decoration:none;"></a>';                                        
    controlUI_1.appendChild(controlText_1);
    controlDiv.index=1;

    // Creamos el DIV que contendrá al botón y asignamos los estilos
    var controlUI_2 = document.createElement('div');
    controlUI_2.id = 'btnOrtofotos';
    controlUI_2.style.backgroundColor = 'white';
    controlUI_2.style.borderStyle = 'solid';
    controlUI_2.style.borderWidth = '1px 1px 0px 1px';
    controlUI_2.style.borderColor = 'rgb(178, 177, 138)';
    controlUI_2.style.borderRadius = '2px';
    controlUI_2.style.boxShadow = '0px 2px 4px -1px rgba(0, 0, 0, 0.3)';
    controlUI_2.style.marginTop = '5px';
    controlUI_2.style.marginRight = '5px';
    controlUI_2.style.marginBottom = '0px';
    controlUI_2.style.marginLeft = '5px';
    controlUI_2.style.paddingRight = '4px';
    controlUI_2.style.paddingBottom = '0px';
    controlUI_2.style.paddingLeft = '4px';
    controlUI_2.style.cursor = 'pointer';
    controlUI_2.style.textAlign = 'center';
    controlUI_2.style.display = 'block';
    controlUI_2.title = 'Haz click aquí para ver el mapa de ortofotos';
    controlDiv.appendChild(controlUI_2);
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlUI_2);

    // Creamos el DIV interno que tendrá la etiqueta y HTML del botón
    var controlText_2 = document.createElement('div');
    controlText_2.style.fontFamily = 'Roboto,Arial,sans-serif';
    controlText_2.style.fontSize = '11px';
    controlText_2.style.lineHeight = '14.5px';
    controlText_2.style.paddingTop = '2px';
    controlText_2.style.paddingLeft = '4px';
    controlText_2.style.paddingRight = '4px';
    controlText_2.innerHTML = 'Ortofoto';                                       
    controlUI_2.appendChild(controlText_2);
    controlDiv.index=2;

    //En caso de que sea el botón de Ortofotos, lanzamos el evento para mostrar el mapa
    google.maps.event.addDomListener(controlUI_2, 'click', function() {
        MuestraMapaOrtofotos();
    });

    // Creamos el DIV que contendrá al botón y asignamos los estilos
    var controlUI_3 = document.createElement('div');
    controlUI_3.id = 'btnCapas';
    controlUI_3.style.backgroundColor = 'white';
    controlUI_3.style.borderStyle = 'solid';
    controlUI_3.style.borderWidth = '1px 1px 0px 1px';
    controlUI_3.style.borderColor = 'rgb(178, 177, 138)';
    controlUI_3.style.borderRadius = '2px';
    controlUI_3.style.boxShadow = '0px 2px 4px -1px rgba(0, 0, 0, 0.3)';
    controlUI_3.style.marginTop = '5px';
    controlUI_3.style.marginRight = '5px';
    controlUI_3.style.marginBottom = '0px';
    controlUI_3.style.paddingRight = '4px';
    controlUI_3.style.paddingBottom = '0px';
    controlUI_3.style.paddingLeft = '4px';
    controlUI_3.style.cursor = 'pointer';
    controlUI_3.style.textAlign = 'center';
    controlUI_3.style.display = 'block';
    controlUI_3.title = 'Haz click aquí para ver los puntos de interés';
    controlDiv.appendChild(controlUI_3);
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlUI_3);

    // Creamos el DIV interno que tendrá la etiqueta y HTML del botón
    var controlText_3 = document.createElement('div');  
    controlText_3.style.fontFamily = 'Roboto,Arial,sans-serif'; 
    controlText_3.style.fontSize = '11px';  
    controlText_3.style.lineHeight = '14.5px';  
    controlText_3.style.paddingTop = '2px'; 
    controlText_3.style.paddingLeft = '4px';    
    controlText_3.style.paddingRight = '12px';  
    controlText_3.innerHTML = '<a id="btnCapas" href="javascript:void(0);" onclick="muestraCapasMapa();">Más información<span id="flecha"></span></a><div id="capas_mapa" class="ocultar" onload="mostrarCapas();"><div><input type="checkbox" checked id="Capa_1" for="Capa_1" onclick="chequearCapas();" /><label for="Capa_1"  style="background-image:url(<url_ico_layer1>)">Ruta Gran Senda</label></div><div><input type="checkbox"id="Capa_2" for="Capa_2" onclick="chequearCapas();" /><label for="Capa_2"  style="background-image:url(<url_ico_layer2>)">Gran Recorrido</label></div><div><input type="checkbox"id="Capa_3" for="Capa_3" onclick="chequearCapas();" /><label for="Capa_3"  style="background-image:url(<url_ico_layer3>)">Pequeño Recorrido</label></div></div>';                                         
    controlUI_3.appendChild(controlText_3);

    controlDiv.index=3;            
}

function chequearCapas(){
    var vacio = true;
    var boundsCapas = new google.maps.LatLngBounds();

    geoXml_1.hideDocument();
    if (document.getElementById("Capa_1")){
        if (document.getElementById("Capa_1").checked){
            geoXml_1.showDocument();
            boundsCapas.union(bounds_1);
            vacio = false;
        }
        else{
                geoXml_1.hideDocument();
        }
    }else{
       geoXml_1.showDocument();
    } 

    geoXml_2.hideDocument();
    if (document.getElementById("Capa_2")){
        if (document.getElementById("Capa_2").checked){
            geoXml_2.showDocument();
            boundsCapas.union(bounds_2);
            vacio = false;
        }else{
            geoXml_2.hideDocument();
        }
    }else{
       geoXml_1.showDocument();
    } 

    geoXml_3.hideDocument();
    if (document.getElementById("Capa_3")){
        if (document.getElementById("Capa_3").checked){
            geoXml_3.showDocument();
            boundsCapas.union(bounds_3);
            vacio = false;
        }else{
            geoXml_3.hideDocument();
        }
    }else{
       geoXml_1.showDocument();
    } 

    if (vacio){
        //Manilva: 36.376063, -5.250776
        //Nerja: 36.757568, -3.872232
        //Alameda: 37.208805, -4.659323
        point = new google.maps.LatLng(
            parseFloat(36.376063),
            parseFloat(-5.250776)
        );
        boundsCapas.extend(point);   //Añadimos puntos

        point = new google.maps.LatLng(
            parseFloat(36.757568),
            parseFloat(-3.872232)
        );
        boundsCapas.extend(point);   //Añadimos puntos

        point = new google.maps.LatLng(
            parseFloat(36.208805),
            parseFloat(-4.659323)
        );
        boundsCapas.extend(point);   //Añadimos puntos
    }
    if (map_1!=null){
        map_1.fitBounds(boundsCapas);
    }
}

PD: You can load the map using initialize_1(). It's too heavy, I hope it will for you to explain my problem better.

FINAL SOLUTION

I think I've found the solution to my problem. Finally I only create one geoXml object. I loaded four layers using parse(<url>):

<url_layer>/location.asp
<url_layer>/rute.asp?tip=1
<url_layer>/rute.asp?tip=2
<url_layer>/rute.asp?tip=3"

If you checked geoxml.docs.length you get 2!! So, if I show or hide the layer2 o layer3 could be wrong. The solution has been call to differents urls to get geoxml.docs.length==4:

<url_layer>/location.asp
<url_layer>/rute1.asp
<url_layer>/rute2.asp
<url_layer>/rute3.asp
2

There are 2 answers

0
Andynedine On BEST ANSWER

FINAL SOLUTION

I think I've found the solution to my problem. Finally I only create one geoXml object. I loaded four layers using parse(<url>):

<url_layer>/location.asp
<url_layer>/rute.asp?tip=1
<url_layer>/rute.asp?tip=2
<url_layer>/rute.asp?tip=3"

If you checked geoxml.docs.length you get 2!! So, if I show or hide the layer2 o layer3 could be wrong. The solution has been call to differents urls to get geoxml.docs.length==4:

<url_layer>/location.asp
<url_layer>/rute1.asp
<url_layer>/rute2.asp
<url_layer>/rute3.asp
0
geocodezip On

This works for me:

geoXml = new geoXML3.parser({
               map: map,
               infoWindow: infowindow,
               singleInfoWindow: true
             });
geoXml.parse(filename);
geoXml.parse("TrashDays40.xml");
geoXml.parseKmlString('<kml xmlns="http://www.opengis.net/kml/2.2"><Document><Placemark><name><![CDATA[]]>Polygon</name><description><![CDATA[]]></description><Polygon><extrude>1</extrude><altitudeMode>relativeToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>-93.46008301171878,31.329035778926478,0 -98.30505371484378,31.40065516914794,0 -97.37121582421878,30.106233605369603,0 -92.65808105859378,30.14749530904506,0</coordinates></LinearRing></outerBoundaryIs> </Polygon></Placemark></Document></kml>');

working example (with 4 files)