Here Map Angular组件在模态组件中未加载

huangapple go评论75阅读模式
英文:

Here Map Angular Component Not loading in Modal Component

问题

使用Here地图来显示货物的停靠点,其中使用货物ID来获取这些停靠点的详细信息。从模态组件加载Here地图。

jsmap-show-modal.component.html

<app-modal [title]="header">
  <ng-template appModalBody>
    <div><jsapp-map [shipmentId]="shipmentId"></jsapp-map></div>
  </ng-template>
</app-modal>

jsmap-show-modal.component.ts

import { Component, Inject, Input, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material';

@Component({
  selector: 'app-jsmap-show-modal',
  templateUrl: './jsmap-show-modal.component.html',
  styleUrls: ['./jsmap-show-modal.component.scss']
})
export class JsMapShowModalComponent implements OnInit {
  public shipmentId: string;
  public header: string;

  constructor(@Inject(MAT_DIALOG_DATA) public data: any){
    console.log(data);
    this.header = data.header;
    this.shipmentId = data.shipmentId;
  }

  ngOnInit() {}
}

在@NgModule指令的entryComponents属性中声明了jsModalComponent。

以下是jsmap.component.ts中的代码:

@Component({
  selector: 'jsapp-map',
  templateUrl: './jsmap.component.html',
  styleUrls: ['./jsmap.component.scss']
})
export class JsmapComponent {
  @Input() shipmentId: string;
  private platform: any;
  private map: any;
  private router: any;
  private locations: any;
  private waypoints: any;
  private tripId: string;

  constructor(
    private jsmapService: JsmapService,
    private route: ActivatedRoute) {
    this.platform = new H.service.Platform({
      apikey: 'MY_API_KEY' // 请将此处替换为您的API密钥
    });
  }

  ngOnInit(): void {
    this.initializeMap();
    this.calculateRoute();
  }

  // 其余代码请参考您提供的原始代码
}

jsmap.component.html

<div id="mapContainer" style="width: 100%; height: 500px;"></div>

请注意替换MY_API_KEY为您自己的Here地图API密钥。希望这可以帮助您解决问题。

英文:

Using Here Map to show stops for a shipment, where using the shipment id to fetch the details of those stops. Loading the here map from the Modal Component.

jsmap-show-modal.component.html

&lt;app-modal [title]=&quot;header&quot;&gt;
  &lt;ng-template appModalBody&gt;
    &lt;div&gt;&lt;jsapp-map [shipmentId]=&quot;shipmentId&quot;&gt;&lt;/jsapp-map&gt;&lt;/div&gt;
  &lt;/ng-template&gt;
&lt;/app-modal&gt;

jsmap-show-modal.component.ts

import { Component, Inject, Input, OnInit } from &#39;@angular/core&#39;;
import { MAT_DIALOG_DATA } from &#39;@angular/material&#39;;

@Component({
  selector: &#39;app-jsmap-show-modal&#39;,
  templateUrl: &#39;./jsmap-show-modal.component.html&#39;,
  styleUrls: [&#39;./jsmap-show-modal.component.scss&#39;]
})
export class JsMapShowModalComponent implements OnInit {
  public shipmentId: string;
  public header: string;
  constructor(@Inject(MAT_DIALOG_DATA) public data: any){
    console.log(data);
    this.header = data.header;
    this.shipmentId = data.shipmentId ;
  }
  ngOnInit() {}
}

Declared the jsModalComponent at necessary modules at the entryComponents property in the @NgModule directive.

Here is the code in jsmap.component.ts

@Component({
  selector: &#39;jsapp-map&#39;,
  templateUrl: &#39;./jsmap.component.html&#39;,
  styleUrls: [&#39;./jsmap.component.scss&#39;]
})
export class JsmapComponent {
@Input() shipmentId: string;
  private platform: any;
  private map: any;
  private router: any;
  private locations: any;
  private waypoints: any;
  private tripId: string;

  constructor(
    private jsmapService: JsmapService,
    private route: ActivatedRoute) {
    this.platform = new H.service.Platform({
      apikey: &lt;&lt;MY_API_KEY&gt;&gt;
    });
  }

ngOnInit(): void {
    this.initializeMap();
    this.calculateRoute();
  }

initializeMap(): void {
    const defaultLayers = this.platform.createDefaultLayers();
    this.map = new H.Map(document.getElementById(&#39;mapContainer&#39;), defaultLayers.vector.normal.map, {
      zoom: 10,
      center: { lat: 40.397694, lng: -105.073181 },
      pixelRatio: window.devicePixelRatio || 1
    });
    const ui = H.ui.UI.createDefault(this.map, defaultLayers);
    const behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
  }

  calculateRoute(): void {
    this.fetchStopDetailsAndGenerateWaypoints();
  }

onRouteSuccess(result: any): void {
    const route = result.response.route[0];

    const lineString = new H.geo.LineString();
    route.shape.forEach((point: any) =&gt; {
      const parts = point.split(&#39;,&#39;);
      lineString.pushLatLngAlt(parts[0], parts[1]);
    });

    const routePolyline = new H.map.Polyline(lineString, {
      style: { strokeColor: &#39;blue&#39;, lineWidth: 3 }
    });

    this.map.addObject(routePolyline);

    route.waypoint.forEach((waypoint: any, index: number) =&gt; {
      const marker = new H.map.Marker({
        lat: waypoint.mappedPosition.latitude,
        lng: waypoint.mappedPosition.longitude
      });
      this.map.addObject(marker);
      marker.label = index + 1;
    });

    this.map.getViewModel().setLookAtData({ bounds: route.boundingBox });
  }

async fetchStopDetailsAndGenerateWaypoints(): Promise&lt;void&gt; {
    const request = new StopDetailsRequest(null, this.shipmentId);
    try {
      const response = await this.jsmapService.getStopDetails(request).toPromise();
      if (response.data &amp;&amp; response.data.StopDetailDTOList) {
        const stopDetails: StopDetail[] = response.data.StopDetailDTOList.map(item =&gt; ({
          stopName: item.StopName,
          stopAlias: item.StopAlias,
          shipmentName: item.ShipmentName,
          stopSequence: item.StopSequence,
          latitude: item.Latitude,
          longitude: item.Longitude,
          estimatedDispatcherArrival: item.EstimatedDispatcherArrival,
          estimatedDispatcherDeparture: item.EstimatedDispatcherDeparture
        }));

        this.locations = this.generateLocationsFromDTO(stopDetails);
        this.waypoints = this.generateWaypoints(this.locations);

        // Use locations and waypoints as needed
        console.log(this.locations);
        console.log(this.waypoints);
        const routingParameters: { [key: string]: any } = {
          mode: &#39;fastest;car&#39;,
          representation: &#39;display&#39;
        };

        for (const key in this.waypoints) {
          if (this.waypoints.hasOwnProperty(key)) {
            routingParameters[key] = this.waypoints[key];
          }
        }

        this.router = this.platform.getRoutingService();
        this.router.calculateRoute(routingParameters, this.onRouteSuccess.bind(this), this.onRouteError.bind(this));
      } else {
        console.error(&#39;Invalid response format: stopDetailDTOList is not an array&#39;);
      }
    } catch (error) {
      // Handle the error here
      console.error(error);
    }
  }

jsmap.component.html

&lt;div id=&quot;mapContainer&quot; style=&quot;width: 100%; height: 500px;&quot;&gt;&lt;/div&gt;

On debugging, Can see that the code is working and it is fetching the necessary details to populate the lat and long on the map but somehow it is not loading on the modal box.

Output:

Here Map Angular组件在模态组件中未加载

Please help and guide!

答案1

得分: 0

ngAfterViewInit():void {
window.setTimeout(() => {
this.initializeMap();
this.calculateRoute();
}, 500);
}

添加延迟成功!
由于模态框的DOM没有及时加载,来自Here Map API的响应找不到mapContainer id,因此无法初始化地图,然后用于停靠点的纬度和经度的其他请求未发送到Here Map API。

英文:
 ngAfterViewInit(): void {
 window.setTimeout(()=&gt;{
  this.initializeMap();
  this.calculateRoute();
}, 500);

Adding a delay worked!
Since the modal DOM didn't load in time and the response coming in from the Here Map API couldn't find the mapContainer id, due to which it was unable to initialise the map and then other requests to map the lat and long for the stop didn't go to Here map API.

答案2

得分: 0

HERE Maps API for JavaScript库对Angular框架一无所知,而Angular框架对HERE Maps API for JavaScript也一无所知。

因此,您需要保持Angular的生命周期,它提供了许多钩子/事件供您使用。

请参阅以下示例(如何使用ngAfterViewInit):https://developer.here.com/documentation/maps/3.1.42.2/dev_guide/topics/angular-practices.html

import { Component, ViewChild, ElementRef } from '@angular/core';
import H from '@here/maps-api-for-javascript';

@Component({
  selector: 'app-jsmap',
  templateUrl: './jsmap.component.html',
  styleUrls: ['./jsmap.component.css']
})
export class JsmapComponent {

  private map?: H.Map;

  @ViewChild('map') mapDiv?: ElementRef; 

  ngAfterViewInit(): void {
    if (!this.map && this.mapDiv) {
      // 实例化平台、默认图层和地图。
      const platform = new H.service.Platform({
        apikey: '{YOUR_API_KEY}'
      });
      const layers = platform.createDefaultLayers();
      const map = new H.Map(
        this.mapDiv.nativeElement,
        // 添加类型断言到图层对象以避免编译期间的任何类型错误。
        (layers as any).vector.normal.map,
        {
          pixelRatio: window.devicePixelRatio,
          center: {lat: 0, lng: 0},
          zoom: 2,
        },
      );
      this.map = map;
    }
  }
}

请将 {YOUR_API_KEY} 替换为您自己的API密钥。

英文:

HERE Maps API for JavaScript library nothing knows about Angular framework and Angular framework nothing knows about HERE Maps API for JavaScript.

Therefore you need to keep Angular's lifecycle which provides many hooks/events for it.

See please the example (how to use ngAfterViewInit) on: https://developer.here.com/documentation/maps/3.1.42.2/dev_guide/topics/angular-practices.html

 import { Component, ViewChild, ElementRef } from &#39;@angular/core&#39;;
 import H from &#39;@here/maps-api-for-javascript&#39;;

 @Component({
   selector: &#39;app-jsmap&#39;,
   templateUrl: &#39;./jsmap.component.html&#39;,
   styleUrls: [&#39;./jsmap.component.css&#39;]
 })
 export class JsmapComponent {

   private map?: H.Map;

   @ViewChild(&#39;map&#39;) mapDiv?: ElementRef; 

   ngAfterViewInit(): void {
     if (!this.map &amp;&amp; this.mapDiv) {
       // Instantiate a platform, default layers and a map as usual.
       const platform = new H.service.Platform({
         apikey: &#39;{YOUR_API_KEY}&#39;
       });
       const layers = platform.createDefaultLayers();
       const map = new H.Map(
         this.mapDiv.nativeElement,
         // Add type assertion to the layers object... 
         // ...to avoid any Type errors during compilation.
         (layers as any).vector.normal.map,
         {
           pixelRatio: window.devicePixelRatio,
           center: {lat: 0, lng: 0},
           zoom: 2,
         },
       );
       this.map = map;
     }
   }
 }

huangapple
  • 本文由 发表于 2023年6月22日 15:14:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定