首页 > 解决方案 > 在 Ionic 中生成 OpenLayers 地图作为组件

问题描述

Ionic v4 和 OpenLayers v5.3

我正在尝试生成一个 OL 地图作为组件,但唯一加载的是图标。似乎样式和 JS 配置没有正确加载,但我不知道为什么。我能够生成在主页配置文件 (home.page.ts) 中注入函数的地图,但地图的质量低且模糊。

在尝试解决此问题时,我发现有人建议将地图加载为组件,所以我来了。我上次使用 Ionic 时,他刚刚切换到版本 3,所以我有点生疏,可能会遗漏一些东西。

open-layers.component.ts 代码:

import { Component, OnInit, ElementRef, ViewChild, Renderer } from '@angular/core';
import { Map } from 'ol';
import { OSM } from 'ol/source.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';

@Component({
  selector: 'app-open-layers',
  templateUrl: './open-layers.component.html',
  styleUrls: ['./open-layers.component.scss'],
})

export class OpenLayersComponent implements OnInit {
    @ViewChild('mapRef') mapRef: ElementRef;

    constructor() {}

    ngOnInit() {

        console.log('Hello');

        var map = new Map({
            layers: [
                new TileLayer({ 
                    source: new OSM()
                })],
            target: document.getElementById('map'), 
            view: new View({
              center: [0, 0],
              zoom: 3
            })
        });
    }
}

在 open-layers.component.html 里面:

<div #mapRef id="map" class="map"></div>

home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <app-open-layers></app-open-layers>
</ion-content>

标签: angularionic-frameworkopenlayersionic4

解决方案


由于robinyo 链接,我能够将地图生成为组件。我需要改变的是:

在代码开头将地图变量定义为 OL Map 类,并在 ngOnInit() 中加载地图。这也会加载在前一个示例中未加载的样式按钮。我仍然需要更新地图的大小以显示他。手机屏幕模糊似乎是设备问题,如果我尝试打开OL在线示例页面,它也是模糊的。

openlayers.component.ts

import { Component, OnInit, Renderer, ViewChild } from '@angular/core';
import { NavController, Platform } from '@ionic/angular';
import { Map } from 'ol';
import { OSM, Vector as VectorSource } from 'ol/source.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';

@Component({
  selector: 'app-openlayers',
  templateUrl: './openlayers.component.html',
  styleUrls: ['./openlayers.component.scss'],
})

export class OpenlayersComponent implements OnInit {

    map: Map;

    constructor() { }

    ngOnInit() {
        this.map = new Map({
          layers: [
            new TileLayer({ 
                source: new OSM()
            })],
          target: document.getElementById('map'),
          view: new View({
            center: [0, 0],
            zoom: 3
          })
        });

        setTimeout(() => {
          this.map.updateSize();
        }, 500);
    }
}

主页.html

<ion-header>
    <ion-toolbar>
        <ion-title>
            Ionic Blank
        </ion-title>
    </ion-toolbar>
    <link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css">
    <style>html, body { margin: 0; }</style>
</ion-header>

<ion-content>
    <app-openlayers></app-openlayers>
</ion-content>

openlayers.component.html

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

推荐阅读