我要使用Angular和leaflet了

有些事情需要使用Angular来使用OpenSteetMap。因为略感觉用Leaflet这个门槛相对较低,但意外地遇到了一些困难,所以写个备忘录。

的/目标/目的

使用Angular中的leaflet,显示OpenStreetMap,并在其上显示图形绘制工具和标记。
本次将在app.component.html中进行显示。

用技术

    • Angular4 (Angular-CLIを使った)

 

    leaflet関連のライブラリ

步骤

如果没有安装Angular-CLI的人

sudo npm install -g angular-cli

我们先创建一个应用程序,首先在终端上创建。

ng new angular-leaflet

进入应用程序目录。

cd angular-leaflet

按照文件中的指示,进行安装。

npm install leaflet
npm install leaflet-draw
npm install @asymmetrik/ngx-leaflet
npm install @asymmetrik/ngx-leaflet-draw
npm install --save-dev @types/leaflet
npm install --save-dev @types/leaflet-draw

我们会开始实际进行引入。

在app.module.ts中进行编写。
导入并注册库。

import { LeafletModule } from '@asymmetrik/ngx-leaflet';
import { LeafletDrawModule } from '@asymmetrik/ngx-leaflet-draw';

()

imports: [
   ...
   LeafletModule.forRoot(),
   LeafletDrawModule.forRoot()
]

()

编辑app.component.ts文件。
导入leaflet库(在第二行)。

import { Component } from '@angular/core';
import * as leaflet from 'leaflet'; 

另外,在类中描述必需的变量。

export class AppComponent {
  title = 'app';
  //地図自体の描写に必要なoptions
  options = {
    layers: [
      leaflet.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '...' })
    ],
    zoom: 40,
    center: leaflet.latLng(35.170915, 136.881537)
  };

  //マーカーと円を名古屋中心にあらかじめ配置する値
  layers = [
    leaflet.circle([ 35.170915, 136.881537 ], { radius: 5000 }),
    leaflet.marker([ 35.170915, 136.881537 ], {
      icon: leaflet.icon({
        iconSize: [ 25, 41 ],
        iconAnchor: [ 13, 41 ],
        iconUrl: 'assets/marker-icon.png',
        shadowUrl: 'assets/marker-shadow.png'
      })
   })
];

  //図形描写ツールに関する値
  drawOptions = {
    position: 'topright',
    draw: {
       marker: {
          icon: leaflet.icon({
              iconSize: [ 25, 41 ],
              iconAnchor: [ 13, 41 ],
              iconUrl: 'assets/marker-icon.png',
              shadowUrl: 'assets/marker-shadow.png'
          })
       },
       polyline: false,
       circle: {
           shapeOptions: {
               color: '#aaaaaa'
           }
       }
    }
 };
}

请在.angular-cli.json文件中添加样式表链接。

{
    ...
    "apps": [
        {
            ...
            "styles": [
                "styles.css",
                "../node_modules/leaflet/dist/leaflet.css"
            ],
            ...
        }
    ]
    ...
}

另外,还需要为标记笔添加以下内容。

{
  "project": {
    ...
  },
  "apps": [
    {
      ...
      "assets": [
        "assets",
        "favicon.ico",
        {
          "glob": "**/*",
          "input": "../node_modules/leaflet/dist/images",
          "output": "./assets/"
        }
      ]
    }
  ]
}

只要不给app.component.html指定高度,地图的高度就会变为0,所以需要height指定。

<div leaflet style="height: 400px;"
     leafletDraw
     [leafletOptions]="options"
     [leafletLayers]="layers"
     [leafletDrawOptions]="drawOptions">

最后启动Angular!

ng serve

如果在浏览器中访问本地主机,应该会显示名古屋!右上角还应该显示一个绘制圆形工具!

广告
将在 10 秒后关闭
bannerAds