I'm trying to use the Google Maps Api on ReactJS with the least npm modules possible. So I'm adding the script to the window object myself. But Typescript jumps after a saying: "Property 'google' does not exist on type 'Window'".
I tried adding a property google: any to the Window interface but it doesn't work, and I can't find the proper interface inside the google types.
This is my code:
private initMap = () => {
this.setState({
map: new window.google.maps.Map(document.getElementById("map"), {
center: {
lat: this.state.userPosition.lat,
lng: this.state.userPosition.lng
},
zoom: this.state.zoom,
mapTypeId: window.google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
})
});
this.setState({
rangeCircle: new window.google.maps.Circle({
strokeColor: "#007AFF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#007AFF",
fillOpacity: 0.35,
map: this.state.map,
center: {
lat: this.state.userPosition.lat,
lng: this.state.userPosition.lng
},
radius: this.state.radius * 1000
})
});
this.setState({
centerMarker: new window.google.maps.Marker({
icon: { locationIcon },
map: this.state.map,
position: this.state.userPosition
})
});
};
private renderMap = () => {
loadScript(
"https://maps.googleapis.com/maps/api/js?key=*********&callback=initMap"
);
window.initMap = this.initMap;
};
}
function loadScript(url: string) {
const index = window.document.getElementsByTagName("script")[0];
const script = window.document.createElement("script");
script.src = url;
script.async = true;
script.defer = true;
if (index.parentNode) {
index.parentNode.insertBefore(script, index);
}
}
--------------UPDATE------------------
I created this interface:
interface IGoogle {
maps: {
Circle: google.maps.Circle;
Map: google.maps.Map;
Marker: google.maps.Marker;
}
}
And added a google property inside Window:
interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch, WindowOrWorkerGlobalScope, WindowEventHandlers {
google: IGoogle;
initMap: () => void;
And it still returns the same error.
You need Google Map's TypeScript definition, this can be achieved with the command npm i @types/google.maps --save-dev
Revision: per @timarcosdias, the package is updated to @types/google.maps
why you are using the window.google
and not like this
just add this on top of your class outside
declare const google: any;
and then used like this.
map: new google.maps.Map(document.getElementById("map"),
or install the typings.
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