how to use google maps apis in angular 4.
I am trying to use google maps. gave reference to google maps api with the key. but not able to use it. while integrating it . got the error google is not defined and to resolve i declared var google:any error got resolved but it is not building the map and now i am getting "Cannot read property 'firstChild' of null"
You can try this:
Step 1: npm install @types/googlemaps --save
Step 2 : Add below line into your index.html
with correct google API key ( Don't forget it )
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY&callback=initMap"
async defer></script>
Step 3: Add below line to your html where you want to add google map
<div #googleMap style=”width:300%;height:300px”></div>
Step 4: Now you add below code into your angular component
import { Component, ViewChild } from '@angular/core';
import { } from '@types/googlemaps';
@Component({
selector: 'map-component',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent {
@ViewChild('googleMap') gmapElement: any;
map: google.maps.Map;
ngOnInit() {
var mapProp = {
center: new google.maps.LatLng(28.4595, 77.0266),
zoom: 14,
// mapTypeId: google.maps.MapTypeId.ROADMAP
mapTypeId: google.maps.MapTypeId.HYBRID
// mapTypeId: google.maps.MapTypeId.SATELLITE
// mapTypeId: google.maps.MapTypeId.TERRAIN
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
var marker = new google.maps.Marker({ position: mapProp.center });
marker.setMap(this.map);
var infowindow = new google.maps.InfoWindow({
content: "Hey, We are here"
});
infowindow.open(this.map, marker);
}
}
Congratulations !!!
Here is the snapshot what you did.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With