Mapbox In Angular

You can install the Mapbox-gl package using the following npm :-

npm install mapbox-gl

Now, add Mapbox API key to the environment.ts

export const environment = {
  production: false,
  mapbox: {
    accessToken: <API_KEY>
  }
};

Next step is to open app.component.ts file and put following code

import { Component, OnInit } from '@angular/core';
import * as mapboxgl from 'mapbox-gl';
import { TokenStorageService } from 'src/app/_services/token-storage.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class LoginComponent implements OnInit {

  map!: mapboxgl.Map;
  style = 'mapbox://styles/mapbox/streets-v11';
  lat = 37.75;
  lng = -122.41;

  constructor(private tokenService: TokenStorageService) { }

  ngOnInit() {
    (mapboxgl as typeof mapboxgl).accessToken = environment.mapbox.accessToken
    this.map = new mapboxgl.Map({
      container: 'map',
      style: this.style,
      zoom: 13,
      center: [this.lng, this.lat]
    });

    this.map.addControl(new mapboxgl.NavigationControl());
  }

  getdata() {
    const response = this.tokenService.getData()
    console.log(response)
  }
}

Then open app.component.html file and put following code

<h2 class="text-center">Google Mapbox In Angular</h2>
<div class="map" id="map" class="match-parent"></div>

In last step open app.component.css file and put following code

.match-parent {
    width: 50%;
    height: 50%;
    margin: auto;
  }

Output :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories