Ионная интеграция OpenStreetMap с Leaflet - PullRequest
0 голосов
/ 28 мая 2018

Я интегрирую Ionic App с OSM, используя Leaflet.У меня есть внутри файла page.html, а остальная часть кода находится внутри моего файла page.ts.Итак, я не использую @ViewChild (), чтобы найти этот div.Как, Leaflet's L.map ('map') должен найти его.Я инициализирую свою карту в ionViewDidLoad и выполняю тяжелую работу в ionViewDidEnter, такую ​​как преобразование данных osm, которые извлекаются из почтового запроса, в данные geoJSON, а затем добавление большого количества маркеров на карту.Я вроде пытаюсь освободить ресурсы в ionViewDidLeave, делая this.map = null; .Это правильная реализация?Кто может что-то посоветовать в плане реализации.Потому что когда я прокручиваю, страница как бы замерзает.

ionViewDidLoad() {
    this.map = L.map('map').setView([41.0131, 28.9641], 18);
    L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
      maxZoom: 18
    }).addTo(this.map);
}

ionViewDidEnter() {
    this.filterProvider.getData(resource).subscribe(data => {
      if (this.map !== null) {
        L.geoJSON(osmtogeojson(data), {
          style: function(feature) {
              return {
                color: "#0288D1"
              };
          },
          pointToLayer: function(feature, latlng) {
            return L.marker(latlng, {
              icon: L.icon({
                iconUrl: 'assets/map/' + resource.toLowerCase() +'.png'
              })
            });
          },
          onEachFeature: function(feature, layer) {
            layer.bindPopup(JSON.stringify(feature.properties));
          }
        }).addTo(this.map);
      }
    });
}

ionViewDidLeave() {
   this.map = null;
   this.selectedResource = null;
}

1 Ответ

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

Он, некоторое время назад я опубликовал в блоге codigo200 пример Ionic3 + Leaflet, который решает вашу проблему, код в github, вы можете прочитать объяснение здесь .

// atributes

map: L.Map;
center: L.PointTuple;
tempIcon: any;

ionViewDidLoad() {

this.center = [23.03, -81.57]; //a place in Cuba

this.map = L.map('map', {
center: this.center,
zoom: 13
});

//Adicionamos la ruta de OSM.
L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© Código 200'
})
.addTo(this.map);

this.mensaje("Pulse sobre un punto en el mapa para añadir un nuevo lugar");

this.tempIcon = L.icon({
iconUrl: 'assets/imgs/marker.png',
shadowUrl: '',
iconSize: [32, 32], // size of the icon
shadowSize: [0, 0], // size of the shadow
iconAnchor: [32, 32], // point of the icon which will correspond to markers location
shadowAnchor: [0, 0], // the same for the shadow
popupAnchor: [32, 20] // point from which the popup should open relative to the iconAnchor
});

this.map.on('click', (e) => { this.onMapClick(e) });

}

onMapClick(e) {
let tempMarker = L.marker(e.latlng, { icon: this.tempIcon })
.on('click', this.showMarkerMenu, this)  // Al hacer click, ejecutamos this.showMarkerMenu y le pasamos el contexto (this)
.addTo(this.map);

this.mensaje("Coordinate: " + e.latlng);

}

Итак, я надеюсь, что это решит вашу проблему, помните, что вам нужна ссылка листовка в index.html.

...