In this article, we will learn how to show Google Map using javascript API step by step.
Show Google map in Angular 14+
Create a New map component
ng g c map
Update map.component.html
<div class="map" #map></div>
Generate Google Maps service
ng g service services/google-maps/google-maps
It will Create google-maps service inside the services folder.
Now replace this code with google-maps.service.ts
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root',
})
export class GoogleMapsService {
constructor() {}
loadGoogleMaps(): Promise<any> {
const win = window as any;
const gModule = win.google;
if (gModule && gModule.maps) {
return Promise.resolve(gModule.maps);
}
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src =
'https://maps.googleapis.com/maps/api/js?key=' +
environment.googleMapsApiKey +
'&libraries=places';
script.async = true;
script.defer = true;
document.body.appendChild(script);
script.onload = () => {
const loadedGoogleModule = win.google;
if (loadedGoogleModule && loadedGoogleModule.maps) {
resolve(loadedGoogleModule.maps);
} else {
reject('Google Map SDK is not Available');
}
};
});
}
}
Then update map.component.ts
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnInit,
Output,
Renderer2,
ViewChild,
} from '@angular/core';
import { GoogleMapsService } from 'src/app/services/google-maps/google-maps.service';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss'],
})
export class MapComponent implements OnInit, AfterViewInit {
@ViewChild('map', { static: true }) mapElementRef: ElementRef;
googleMaps: any;
map: any;
center = { lat: 23.01997577399075, lng: 73.07245691797758 };
constructor(
private maps: GoogleMapsService,
private renderer: Renderer2
) {}
ngOnInit(): void {}
ngAfterViewInit() {
this.loadMap();
}
async loadMap() {
try {
let googleMaps: any = await this.maps.loadGoogleMaps();
this.googleMaps = googleMaps;
const mapEl = this.mapElementRef.nativeElement;
const location = new googleMaps.LatLng(this.center.lat, this.center.lng);
this.map = new googleMaps.Map(mapEl, {
center: location,
zoom: 15,
scaleControl: false,
streetViewControl: false,
zoomControl: false,
overviewMapControl: false,
mapTypeControl: false,
mapTypeControlOptions: {
mapTypeIds: [googleMaps.MapTypeId.ROADMAP, 'mapId'],
},
});
const style = [
{
featureType: 'all',
elementType: 'all',
stylers: [{ saturation: -100 }],
},
];
var mapType = new googleMaps.StyledMapType(style, { name: 'Grayscale' });
this.map.mapTypes.set('mapId', mapType);
this.map.setMapTypeId('mapId');
this.renderer.addClass(mapEl, 'visible');
} catch (e) {
console.log(e);
}
}
}
Now update map.component.scss
.map {
height: 30vh;
width: 100%;
background-color: transparent;
}
.map.visible {
opacity: 1;
}
Now your map will be visible on browser
How to add a Marker in Google Maps?
Add the addMarker function as below in map.componenets.ts
as below:
addMarker(location) {
let googleMaps: any = this.googleMaps;
const icon = {
url: 'assets/icons/location-pin.png',
scaledSize: new googleMaps.Size(50, 50),
};
this.marker = new googleMaps.Marker({
position: location,
map: this.map,
icon: icon,
draggable: true,
animation: googleMaps.Animation.DROP,
});
}
Then call this function at bottom of loadMap function
this.addMarker(location);
Now you can also see the marker on the map at the center position.
Top comments (0)