Next.js(TypeScript)中Google Maps InfoWindow.close未定义报错求助
解决方案
1. 安装Google Maps类型依赖
首先需要安装官方的Google Maps TypeScript类型定义,让TypeScript识别google.maps.InfoWindow等相关类型:
npm install @types/google.maps --save-dev # 或使用yarn yarn add @types/google.maps --dev
2. 为iWindow状态指定正确类型
原代码中useState(null)会让TypeScript推断iWindow的类型为null,导致调用close()时触发类型报错。需要显式指定类型为google.maps.InfoWindow | null:
const [iWindow, setIWindow] = useState<google.maps.InfoWindow | null>(null);
3. 添加安全的空值检查
在调用iWindow.close()前,先判断iWindow是否存在,既避免运行时的空值错误,也能解决TypeScript的类型提示问题:
const handleSensorInfoCloseAction = () => { setMarkerData(null); if (iWindow) { iWindow.close(); } }
修正后的完整代码
import SensorInfo from './SensorInfo'; import GoogleMapReact from 'google-map-react'; import { useState } from 'react'; export default function HomeMap() { const [markerData, setMarkerData] = useState(null); // 显式指定iWindow的类型 const [iWindow, setIWindow] = useState<google.maps.InfoWindow | null>(null); const handleMarkerClick = (marker: any) => { setMarkerData(marker.featureData); console.log(marker) }; const handleSensorInfoCloseAction = () => { setMarkerData(null); // 空值检查后再调用close方法 if (iWindow) { iWindow.close(); } } return ( <> <div style={{ height: "700px", width: "100%" }}> <GoogleMapReact yesIWantToUseGoogleMapApiInternals={true} bootstrapURLKeys={{ key: `${process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY}` }} defaultCenter={{ lat: 41.876, lng: -87.624 }} defaultZoom={10} onGoogleApiLoaded={({ map, maps }) => { const newIWindow = new maps.InfoWindow(); setIWindow(newIWindow); const kmlLayer = new maps.KmlLayer( "https://raw.githubusercontent.com/Nathaniael/test/main/test4", { preserveViewport: false, map: map, suppressInfoWindows: true } ); maps.event.addListener(kmlLayer, 'click', function(evt: any) { newIWindow.setContent(evt.featureData.infoWindowHtml); newIWindow.setPosition(evt.latLng); newIWindow.open(map); }) maps.event.addListener(kmlLayer, "click", handleMarkerClick); maps.event.addListener(newIWindow, "closeclick", function() { setMarkerData(null); }) }} > </GoogleMapReact> </div> { markerData && <SensorInfo markerData={markerData} onClose={handleSensorInfoCloseAction}/> } </> ); }
错误原因说明
- 未指定状态类型时,TypeScript会推断
iWindow的类型为null,调用close()自然会提示“方法可能未定义”; - 直接添加空值检查但不指定类型时,TypeScript无法识别
iWindow后续会被赋值为InfoWindow实例,会错误推断其类型为never,从而触发“property close does not exist on type never”报错; - 显式指定
google.maps.InfoWindow | null类型后,TypeScript能正确识别状态的可能取值,配合空值检查即可消除所有类型报错。
内容的提问来源于stack exchange,提问作者Nathaniael
相关产品推荐
相关产品推荐

