简体   繁体   中英

Mapbox markers throws TypeError

I´m trying to add markers to my map from mapbox.

This is my Angular TypeScript code.

export class MappViewComponent implements OnInit {
  map: mapboxgl.Map;
  lat = 41.1293;
  lng = -8.4464;
  style = "mapbox://styles/mapbox/streets-v11";
  zoom = 8;

  constructor(
    private mapService: MapService,
    private nodeService: NodeService
  ) {}

  ngOnInit() {
    this.buildMap(this.map);
    /*var mymap = L.map('mapID').setView([41.260555, -8.436098], 10);
    this.buildMap(mymap);*/
    this.addMarkersLines(this.map);
    new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map);
  }

  /**https://leafletjs.com/reference-1.7.1.html */
  buildMap(map: any) {
    map = new mapboxgl.Map({
      accessToken:
        "accessToken",
      container: "mapID",
      style: this.style,
      zoom: this.zoom,
      center: [this.lng, this.lat],
      antialias: true,
      attributionControl: false,
    });
    map.addControl(new mapboxgl.NavigationControl());

The problem is that, after running in console it throws this error on this line:

new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map); 

ERROR TypeError: t is undefined addTo mapbox-gl.js:35 ngOnInit mapp-view.component.ts:30

Does anyone have this kind of problem?

Most likely the error occurs since this.map is undefined here:

new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map);
                                                            ^^^^^^^^  
                                                            undefined 

The way how function buildMap is implemented, it does not affect the object passed, meaning this.map stays undefined in your case. Try to refactor buildMap function, for example:

buildMap() {
    this.map = new mapboxgl.Map({
      accessToken: MAPBOX_TOKEN,
      container: 'mapID',
      style: this.style,
      zoom: this.zoom,
      center: [this.lng, this.lat],
      antialias: true,
      attributionControl: false,
    });
    this.map.addControl(new mapboxgl.NavigationControl());
 }

Usage

ngOnInit() {
    this.buildMap();
    new mapboxgl.Marker().setLngLat([this.lng, this.lat]).addTo(this.map);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM