I have been struggling for a couple of hours trying to make work googlemaps PlaceResult
in my Angular 2 project that uses Angular-cli
.
I had to install googlemaps
using @types and add it under the attribute "types"
of my tsconfig.json
configuration file.
{
...
"types": [
"google-maps"
]
}
}
And I succeed to use google.maps.places.PlaceResult
in my Angular 2 Component by simply importing it !
import { ActivatedRoute, Params } from "@angular/router";
import { MapsAPILoader } from "angular2-google-maps/core";
import PlaceResult = google.maps.places.PlaceResult;
import GeocoderRequest = google.maps.GeocoderRequest;
...
Several hours later, I had to work with google.maps.Marker
, which is in the same definition file as PlaceResult
and GeocoderRequest
. So I simply imported it as below :
[Line 12] import PlaceResult = google.maps.places.PlaceResult;
[Line 13] import GeocoderRequest = google.maps.GeocoderRequest;
[Line 14] import Marker = google.maps.Marker;
[Line 15] import LatLng = google.maps.LatLng;
...
But I had an unexpected error at runtime saying
Uncaught ReferenceError: google is not defined search.component.ts:14
at Object.444 (search.component.ts:14)
at __webpack_require__ (bootstrap 26c2b97…:52)
at Object.727 (app.config.ts:11)
at __webpack_require__ (bootstrap 26c2b97…:52)
at Object.602 (src async:7)
at __webpack_require__ (bootstrap 26c2b97…:52)
at Object.1258 (.*$:7)
at __webpack_require__ (bootstrap 26c2b97…:52)
at webpackJsonpCallback (bootstrap 26c2b97…:23)
at main.bundle.js:1
Please note that webpack throws this error at line 14 of my component. Meaning that (and correct me if I'm wrong) the previous lines (that uses the same "google") worked well.
Am'I missing something ?
I use :
Regarding import LatLngBounds = google.maps.LatLngBounds;
I find out that I was calling the custructor (new LatLngBounds()
) before the init of Maps api. In fact, I'm using @agm/core;
. And constructor has to be called after load()
as below
ngOnInit() {
this.mapsAPILoader.load().then(() => {
this.page$.subscribe(page => {
if (page && page.content) {
this.latLngBounds = new google.maps.LatLngBounds();
page.content.forEach(w => this.latLngBounds.extend(new google.maps.LatLng(lat, lng)));
}
});
}
);
}
and I added in my typings.d.ts the following import
import {} from '@types/googlemaps';
I solved my problem by having the following config :
1- package.json
"dependencies": {
...
"googlemaps": "^1.12.0",
...
}
2- tsconfig.json
"types": [
...
"googlemaps"
]
3- And add the google api script in my index.html
<head>
...
</head>
<body>
<app-root>Loading...</app-root>
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&language=fr" async defer></script>
</body>
</html>
4- In components, use it like below
declare var google: any;
@Component({
...
})
export class SearchComponent implements OnInit, AfterViewInit {
// Google Maps
bounds: google.maps.LatLngBounds;
markers: google.maps.Marker[];
infoWindow: google.maps.InfoWindow;
}