javascript - שימוש ב-openlayer3 ב-typescript/angular2


יש לי קוד Javascript שמשתמש ב-openLayer3. אני צריך לממש את הקוד הזה בפרויקט Angular2, ב-Typescript.

מישהו יודע איך להשתמש ב-OpenLayer עם Angular2/Typescript בבקשה?

תודה רבה,

ג'ון

תשובה #1

1. אפשרות א' (עבודה עם Angular CLI)

הוסף את Openlayers3 בקובץ .angular-cli.json שלך (שנמצא בשורש הפרויקט שלך):

...
"styles": [
  "../node_modules/openlayers/dist/ol.css"
],
"scripts": [
  "../node_modules/openlayers/dist/ol.js"
],
...

1. אפשרות ב' (לא עובד עם Angular CLI)

הוסף את Openlayers3 ב-index.html שלך (בדרך ה"רגילה"):

<script src="node_modules/openlayers/dist/ol.js"></script> <link rel="stylesheet" href="node_modules/openlayers/dist/ol.css">

2. גש ל-ol מתוך קובץ הטייפסקריפט שלך:

import { AfterViewInit, Component, ElementRef, ViewChild } from "@angular/core";

// This is necessary to access ol3!
declare var ol: any;

@Component({
    selector: 'my-app',
    template: `
    <h3> The map </h3>
    <div #mapElement id="map" class="map"> </div> 
    `
    // The "#" (template reference variable) matters to access the map element with the ViewChild decorator!
})

export class AppComponent implements AfterViewInit {
    // This is necessary to access the html element to set the map target (after view init)!
    @ViewChild("mapElement") mapElement: ElementRef;

    public map: any;

    constructor(){
        var osm_layer: any = new ol.layer.Tile({
            source: new ol.source.OSM()
        });

        // note that the target cannot be set here!
        this.map = new ol.Map({
            layers: [osm_layer],
            view: new ol.View({
            center: ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857'),
            zoom: 2
            })
        });
    }

    // After view init the map target can be set!
    ngAfterViewInit() {
        this.map.setTarget(this.mapElement.nativeElement.id);
    }
}

תשובה #2

לגבי טיפוסים שאולי תתעניין בהם, פרויקט DefinitelyTyped - אפשר למצוא שם openlayers/openlayers.d.ts - כנראה שתצטרך להבין את tsd, קונבנציות של תיקיות וכו'.

לגבי AngularJS 2, בהתחשב בכך שהוא עדיין בבטא, הניסיון מראה שאתה בעיקר לבד. עם זאת, חיפוש בגוגל יכול להפנות אותך למשל ל- https://gist.github.com/borchsenius/5a1ec0b48b283ba65021.

הגישה הרגילה היא קודם להבין את הדרך של AngularJS 2 לפי דוגמאות קיימות כבר. כדאי לשים לב במהרה להרבה הגיון בריא בדרך בה נראות אינטגרציות שונות. לאחר מכן נסו להתאים את מה שאתם רוצים בצורה מתאימה. אז יש את החלק הגדול לתת יותר ולשתף את הידע :)

גם הידע בפתרונות קיימים של AngularJS 1.x כמו במאמר זה עשוי לעזור.