Добавить GPX динамически с открытыми слоями - PullRequest
0 голосов
/ 27 мая 2018

Я пытаюсь показать разные маршруты из файлов gpx, выбрав их из флажков, но векторный слой не появляется.

Я использовал в качестве руководства примеры с веб-страницы OpenLayers: GPXDATA и DragandDrop без результатов.

Main.php

<!DOCTYPE html>
<html>
<head>
    <title>Mapa simple de OpenStreetMap con Open Layers</title>    
    <link rel="stylesheet" href="https://openlayers.org/en/v4.0.1/css/ol.css" type="text/css">
    <script src="https://openlayers.org/en/v4.0.1/build/ol.js"></script>
    <link rel="stylesheet" href="css/main.css" type="text/css">
    <script src="js/main.js"></script>
</head>
<body>
    <h1 id="maintitle">Rutas de Limpieza</h1>
    <div id="content">
        <div id="menu">
            <ul>
                <li>Mostrar Rutas</li>
                <ul>Rutas de Barredoras
                    <li><input id="r1" name="ba_r1" type="checkbox">Ruta B1</li>
                    <li><input name="ba_r2" type="checkbox">Ruta B2</li>
                    <li><input name="ba_r3" type="checkbox">Ruta B3</li>
                </ul>                    
            </ul>
            <button id="sr_btn">Mostrar Rutas Seleccionas</button>
        </div>


        <div id="map" class="map"></div>
    </div>
</body>
</html>

main.js

window.onload = function(){
var defaultStyle = {
    'Point': new ol.style.Style({
      image: new ol.style.Circle({
        fill: new ol.style.Fill({
          color: 'rgba(255,255,0,0.5)'
        }),
        radius: 5,
        stroke: new ol.style.Stroke({
          color: '#ff0',
          width: 1
        })
      })
    }),
    'LineString': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#f00',
        width: 3
      })
    }),
    'Polygon': new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(0,255,255,0.5)'
      }),
      stroke: new ol.style.Stroke({
        color: '#0ff',
        width: 1
      })
    }),
    'MultiPoint': new ol.style.Style({
      image: new ol.style.Circle({
        fill: new ol.style.Fill({
          color: 'rgba(255,0,255,0.5)'
        }),
        radius: 5,
        stroke: new ol.style.Stroke({
          color: '#f0f',
          width: 1
        })
      })
    }),
    'MultiLineString': new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#00f',
        width: 3
      })
    }),
    'MultiPolygon': new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(25,120,255,0.5)'
      }),
      stroke: new ol.style.Stroke({
        color: '#00f',
        width: 1
      })
    })
};

var styleFunction = function(feature, resolution) {
    var featureStyleFunction = feature.getStyleFunction();
    if (featureStyleFunction) {
      return featureStyleFunction.call(feature, resolution);
    } else {
      return defaultStyle[feature.getGeometry().getType()];
    }
};

var map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'map',
    view: new ol.View({
      center: ol.proj.fromLonLat([2.5, 39.5]),
      zoom: 12
    })
});

var btn_sr = this.document.getElementById("sr_btn").addEventListener('click', function(){        
    var vector1 = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'gpx/qq2.gpx',
          format: new ol.format.GPX()
        }),
        style: defaultStyle
    });

    map.addLayer(new ol.layer.Vector({
        renderMode: 'image',
        source: vector1,
        style: styleFunction
    }));
});
}

Что я могу понять из APIфункция map.addLayer должна поместить верхний слой vector1 в коллекцию слоев и показать автоматически, но вместо этого у меня есть эта ошибка: «исключение uncaught: AssertionError: Утверждение не удалось. Подробности см. https://openlayers.org/en/v4.0.1/doc/errors/#41».Что означает: ожидается ol.style.Style или массив ol.style.Style.

Но var defaultStyle уже является массивом стилей, поэтому я не понимаю ошибку.

Спасибо.

1 Ответ

0 голосов
/ 29 мая 2018

У вас есть 2 места, где вы устанавливаете стили в своем коде

  • style: defaultStyle
  • style: styleFunction

styleFunction работает правильно(он возвращает стиль, основанный на типе геометрии).Напротив, defaultStyle не работает, потому что это не «ol.style.Style или массив ol.style.Style».но это объект.

Чтобы устранить проблему, вы можете

  • заменить style: defaultStyle на style: styleFunction.
  • , если ваш GPX содержит только точки, выможно использовать style: defaultStyle['Point']
  • , если он содержит только строки, вы можете использовать style: defaultStyle['LineString']
...