2 votos

Problemas al usar 2 mapas con múltiples capas y evento loadend

Tengo 2 o más mapas con una o n capas en cada mapa. Ahora quiero el zoom a la medida para cada mapa, pero el getDataExtent devuelve sólo para la última capa del último mapa un límite.

¿Puede ayudarme?

Este es el código

var jekyllMapping = (function () {
    return {
        mappingInitialize: function() {
            var maps = document.getElementsByClassName("jekyll-mapping");
            for ( var i = 0; i < maps.length; i++ ) {
                var zoom      = maps[i].getAttribute("data-zoom"),
                    lat       = maps[i].getAttribute("data-latitude"),
                    lon       = maps[i].getAttribute("data-longitude"),
                    layers    = maps[i].getAttribute("data-layers"),
                    title     = maps[i].getAttribute("data-title"),
                    map, markers, center;

                maps[i].setAttribute('id', 'jekyll-mapping' + i);

                markers = new OpenLayers.Layer.Markers("Markers")
                map = new OpenLayers.Map('jekyll-mapping' + i);
                map.addLayer(new OpenLayers.Layer.OSM());
                map.addLayer(markers);
                if (lat && lon) {
                    center = new OpenLayers.LonLat(lon, lat).transform(
                        new OpenLayers.Projection("EPSG:4326"),
                        new OpenLayers.Projection("EPSG:900913"));
                    map.setCenter(center, zoom);
                    markers.addMarker(new OpenLayers.Marker(center));
                }

                if (layers) {
                    // layers are url's to kml files
                    layers = layers.split(' ');
                    while (layers.length > 0){
                        var m = new OpenLayers.Layer.Vector("KML", {
                                strategies: [new OpenLayers.Strategy.Fixed()],
                                protocol: new OpenLayers.Protocol.HTTP({
                                            url: layers.pop(),
                                            format: new OpenLayers.Format.KML({extractStyles: true, extractAttributes: true, maxDepth: 2 })
                                })
                        });
                        if (m) {
                            m.events.register("loadend", m, function () {
                                // raises for all layers but only the last layer on second map gives me a bound, why???
                                var bounds = m.getDataExtent();
                                if (bounds) {
                                    map.zoomToExtent(bounds);
                                }
                            });
                            map.addLayer(m);
                        }
                    }
                }
            }
        }
    };
}());

window.onload = function() { jekyllMapping.mappingInitialize(); }

2voto

Dave Lockhart Puntos 426

Ok, he encontrado mi propia solución (después de algunas reflexiones...), no es perfecta, pero funciona (mira mis comentarios)

var jekyllMapping = (function () {
    return {
        mappingInitialize: function() {
            // holds all created maps
            var allMaps = [];
            // nested for loadend event
            var lastLayer;

            var maps = document.getElementsByClassName("jekyll-mapping");
            for ( var i = 0; i < maps.length; i++ ) {
                var zoom      = maps[i].getAttribute("data-zoom"),
                    lat       = maps[i].getAttribute("data-latitude"),
                    lon       = maps[i].getAttribute("data-longitude"),
                    layers    = maps[i].getAttribute("data-layers"),
                    title     = maps[i].getAttribute("data-title"),
                    map, markers, center;

                // Set an arbitrary id on the element
                maps[i].setAttribute('id', 'jekyll-mapping' + i);

                markers = new OpenLayers.Layer.Markers("Markers")
                map = new OpenLayers.Map('jekyll-mapping' + i);

                // we need the map later for zoomToExtent
                allMaps.push(map);

                map.addLayer(new OpenLayers.Layer.OSM());
                map.addLayer(markers);
                if (lat && lon) {
                    center = new OpenLayers.LonLat(lon, lat).transform(
                        new OpenLayers.Projection("EPSG:4326"),
                        new OpenLayers.Projection("EPSG:900913"));
                    map.setCenter(center, zoom);
                    markers.addMarker(new OpenLayers.Marker(center));
                }

                if (layers) {
                    layers = layers.split(' ');
                    while (layers.length > 0){
                        lastLayer = new OpenLayers.Layer.Vector("KML", {
                                    strategies: [new OpenLayers.Strategy.Fixed()],
                                    protocol: new OpenLayers.Protocol.HTTP({
                                                  url: layers.pop(),
                                                  format: new OpenLayers.Format.KML({extractStyles: true, extractAttributes: true, maxDepth: 2 })
                                              })
                                });
                        map.addLayer(lastLayer);
                    }
                }
            }
            // now try zooming all maps to extent
            if (allMaps.length > 0 && lastLayer) {
                lastLayer.events.register("loadend", lastLayer, function () {
                    while (allMaps.length > 0) {
                        var map = allMaps.pop();
                        var layers = map.getLayersByClass("OpenLayers.Layer.Vector");
                        var bounds;
                        for (i = 0; i < layers.length; i++) {
                            var l = layers[i];
                            if (l) {
                                var b = l.getDataExtent();
                                if (b) {
                                    if (bounds) {
                                        bounds.extend(b);
                                    } else {
                                        bounds = b;
                                    }
                                }
                            }
                        }
                        if (bounds) {
                            map.zoomToExtent(bounds);
                        } else {
                            map.zoomToMaxExtent();
                        }
                    }
                });
            }
        }
    };
}());

window.onload = function() { jekyllMapping.mappingInitialize(); }

aquí hay otro ejemplo sencillo

<html>
    <head>
        <title>OpenLayers Example</title>
        <script src="http://openlayers.org/api/OpenLayers.js"></script>
    </head>
    <body>
        <div style="width:800px; height:350px" id="map1"></div>
        <div style="width:800px; height:350px" id="map2"></div>

        <script defer="defer" type="text/javascript">
            var allMaps = [];
            var map1 = new OpenLayers.Map('map1');
            allMaps.push(map1);
            map1.addLayer(new OpenLayers.Layer.OSM());
            var l1 = new OpenLayers.Layer.Vector("KML", {
                        strategies: [new OpenLayers.Strategy.Fixed()],
                        protocol: new OpenLayers.Protocol.HTTP({
                                      url: "running_001.kml",
                                      format: new OpenLayers.Format.KML({extractStyles: true, extractAttributes: true, maxDepth: 2 })
                                  })
                    });
            var l2 = new OpenLayers.Layer.Vector("KML", {
                        strategies: [new OpenLayers.Strategy.Fixed()],
                        protocol: new OpenLayers.Protocol.HTTP({
                                      url: "running_002.kml",
                                      format: new OpenLayers.Format.KML({extractStyles: true, extractAttributes: true, maxDepth: 2 })
                                  })
                    });
            map1.addLayer(l1);
            map1.addLayer(l2);

            var map2 = new OpenLayers.Map('map2');
            allMaps.push(map2);
            map2.addLayer(new OpenLayers.Layer.OSM());
            var l3 = new OpenLayers.Layer.Vector("KML", {
                        strategies: [new OpenLayers.Strategy.Fixed()],
                        protocol: new OpenLayers.Protocol.HTTP({
                                      url: "running_003.kml",
                                      format: new OpenLayers.Format.KML({extractStyles: true, extractAttributes: true, maxDepth: 2 })
                                  })
                    });
            l3.events.register("loadend", l3, function () {
                if (allMaps.length > 0) {
                    while (allMaps.length > 0) {
                        var map = allMaps.pop();
                        var layers = map.getLayersByClass("OpenLayers.Layer.Vector");
                        var bounds;
                        for (i = 0; i < layers.length; i++) {
                            var l = layers[i];
                            if (l) {
                                var b = l.getDataExtent();
                                if (b) {
                                    if (bounds) {
                                        bounds.extend(b);
                                    } else {
                                        bounds = b;
                                    }
                                }
                            }
                        }
                        if (bounds) {
                            map.zoomToExtent(bounds);
                        } else {
                            map.zoomToMaxExtent();
                        }
                    }
                }
            });
            map2.addLayer(l3);
        </script>
    </body>
</html>

Espero que esto ayude :-)

i-Ciencias.com

I-Ciencias es una comunidad de estudiantes y amantes de la ciencia en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X