A
A
Andrey Astafiev2016-12-22 16:27:36
Angular
Andrey Astafiev, 2016-12-22 16:27:36

How to make Angular 2 and Leaflet friends through a directive?

I can't connect angular second and leaflet together;
position.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-device',
  template: '<div id = "mapid" leaflet style="width: 600px; height: 400px;"></div>'
})


export class PositionComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

position.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { positionRouting } from './position.routing';
import {SmartadminModule} from "../shared/smartadmin.module";
import {PositionComponent} from "./position.component";
import {SmartadminValidationModule } from "../shared/forms/validation/smartadmin-validation.module";
import {LeafletDirective} from "../shared/leaflet/leaflet.directive";

@NgModule({
  imports: [
    CommonModule,
    SmartadminValidationModule,
    positionRouting,
      SmartadminModule
  ],
  declarations: [PositionComponent,LeafletDirective]
})
export class PositionModule { }

leaflet.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
declare var $: any;

@Directive({ selector: '[leaflet]' })

export class LeafletDirective implements OnInit{

    mymap:any;

    constructor(el: ElementRef) {
        //el.nativeElement.style.backgroundColor = 'yellow';
    }

    ngOnInit(){
        System.import('script!leaflet/dist/leaflet.js').then(()=>{
            console.log($(this.el));
            this.mymap = L.map('mapid').setView([51.505, -0.09], 13);

            L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
                maxZoom: 18,
                attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
                '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="http://mapbox.com">Mapbox</a>',
                id: 'mapbox.streets'
            }).addTo(this.mymap );
        })
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
ozknemoy, 2017-03-22
@ozknemoy

here is a ready-made recipe https://github.com/haoliangyu/angular2-leaflet-starter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question