0

in the below posted code i am trying to display a simple map. i referred to openlayer official website and used the code there as mentioned below. the code contains no errors and compiles successfully but there is no map shows up. please let me know how to fix this issue

html:

<a routerLink = "new-cmp">New component</a>
<br />
<br/>
<router-outlet></router-outlet>
<div id="map"></div>

component:

ngOnInit(){

  this.map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: new OSM()
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 0
  })
});
}
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • Are the logic and map div in same component? Check browser console, it might not be able to find the div. Also in angular you use @ViewChild to reference DOM objects, it's the reason your div isn't getting selected. – Maulik Parmar Apr 17 '21 at 06:49
  • @MaulikParmar yes they are in the same component.the browser's console shows no errors.and i am not using ViewChild – Amrmsmb Apr 17 '21 at 07:19
  • Ofc you need `@ViewChild("mapDiv") divView: ElementRef; ` and tag div with `#mapDiv` or do `document.getElementById('map');` to get actual div object, it's likely reference is undefined. – Maulik Parmar Apr 17 '21 at 07:27
  • Also you need to respect component lifecycle thus get reference after it's initialized i.e. `ngAfterViewInit(){ const map = document.getElementById('map'); // map init code } ` – Maulik Parmar Apr 17 '21 at 07:29
  • @MaulikParmar should I just add ‘@viewchild(“mapDiv”)’ – Amrmsmb Apr 17 '21 at 07:30
  • Either way, map div object should be passed to your OSM init function. How you get container reference is irrelevant. – Maulik Parmar Apr 17 '21 at 07:31
  • @MaulikParmar would you please provide an example. In my code I use target:’map’. Should I add ‘@viewchild(“mapDiv”)’?? – Amrmsmb Apr 17 '21 at 07:32
  • It's already answered with much more details, check https://stackoverflow.com/questions/48283679/use-openlayers-4-with-angular-5 – Maulik Parmar Apr 17 '21 at 07:38
  • Also I'd suggest using angular wrapper for it as suggested by others, it's alot easier to include component than redefining everything. – Maulik Parmar Apr 17 '21 at 07:39

0 Answers0