Mapbox GL Popup使用自定义标记设置内容

时间:2018-01-12 15:53:23

标签: javascript jquery angular mapbox mapbox-gl-js

我试图用点击弹出一个标记,到目前为止一直很好, 问题当我试图将弹出窗口的内容设置为我的自定义标记时,例如

let popup = new mapboxgl.Popup()
    .setHTML("<custom-tag></custom-tag>") 

我知道 setDOMContent 的选项,但我没有设法做到正确...它假设使用 document.createElement(&#39; custom-标记&#39;)所以,如果你可以帮助我如何使用自定义组件。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

我能够使用Angular ComponentFactoryResolver使它起作用。有一些设置,但是一旦它开始工作,就可以使用它来呈现所需的任何组件(并将其放置在您想要的任何位置...包括一个mapbox弹出窗口)。

我不确定这是否仍然是执行此操作的“正确”方法(我仍在Angular v5中),但它确实起作用。

1)创建动态组件服务(不记得我在哪里得到的...抱歉,无论您是谁,都没有归属)

import { Injectable, Injector, ApplicationRef, ComponentFactoryResolver, ComponentRef, Type } from '@angular/core'

@Injectable()
export class DynamicComponentService {

    private compRef: ComponentRef<any>;

    constructor(private injector: Injector,
                private resolver: ComponentFactoryResolver,
                private appRef: ApplicationRef) { }


    public injectComponent<T>(component: Type<T>, propertySetter?: (type: T) => void): HTMLDivElement {
        // Remove the Component if it Already Exists
        if (this.compRef) this.compRef.destroy();

        // Resolve the Component and Create
        const compFactory = this.resolver.resolveComponentFactory(component);
        this.compRef = compFactory.create(this.injector);

        // Allow a Property Setter to be Passed in (To Set a Model Property, etc)
        if (propertySetter)
            propertySetter(this.compRef.instance);

        // Attach to Application
        this.appRef.attachView(this.compRef.hostView);

        // Create Wrapper Div and Inject Html
        let div = document.createElement('div');
        div.appendChild(this.compRef.location.nativeElement);

        // Return the Rendered DOM Element
        return div;
    }
}

2)使用该服务在mapbox-gl弹出窗口中呈现您的自定义组件

import { MyCustomMapboxPopup } from "../app/components/my-custom-mapbox-popup.component"
import { DynamicComponentService } from "../services/dynamic-component";

...
// Inside a map.on("click") or wherever you want to create your popup

// Inject Component and Render Down to HTMLDivElement Object
let popupContent = this.dynamicComponentService.injectComponent(
                MyCustomMapboxPopup,
                x => x.model = new PopupModel()); // This Is where You can pass
// a Model or other Properties to your Component

 new mapboxgl.Popup({ closeOnClick: false })
     .setLngLat(...wherever you want the popup to show) 
     .setDOMContent(popupContent)
     .addTo(map);
...

为避免混淆,自定义弹出窗口组件可能类似于:

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

@Component({
    selector: "custom-mapbox-popup",
    templateUrl: "./my-custom-mapbox-popup.component.html"
})
export class MyCustomMapboxPopup {
    public model: PopupModel; // Model Property
}

// HTML
<div class="my-custom-popup">
    <div *ngIf="model">
        <h3>{{this.model.SomeModelProperty}}</h3>
    </div>
</div>