How can I integrate Google Maps APIs inside an Angular 2 component

nix86 picture nix86 · May 19, 2016 · Viewed 41.5k times · Source

I have an Angular 2 component that is defined in the file comp.ts in this way like this:

import {Component} from 'angular2/core';

@component({
    selector:'my-comp',
    templateUrl:'comp.html'
})

export class MyComp{
    constructor(){
    }
}

Because I want the component to show a google map, I have inserted in the file comp.html the following code:

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
  var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>

</html> 

This code has been copied from this link http://www.w3schools.com/googleAPI/google_maps_basic.asp. The problem is that the component doesn't show the map. What have I done wrong?

Answer

Ruslan Abramov picture Ruslan Abramov · Aug 7, 2016

Yeah, you could do so. But there would be an error in typescript compiler, so don't forget to implicitly declare google variable.

declare var google: any;

add this directive right after component import.

import { Component, OnInit } from '@angular/core';
declare var google: any;

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent implements OnInit {
  ngOnInit() {
    var mapProp = {
            center: new google.maps.LatLng(51.508742, -0.120850),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
      var map = new google.maps.Map(document.getElementById("gmap"), mapProp);
  }
}