const google = window.google;
let markers: google.maps.Marker[] = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length === 0) {
return;
}
// Clear out the old markers.
markers.forEach((marker) => {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
places.forEach((place) => {
if (!place.geometry || !place.geometry.location) {
return;
}
const icon = {
url: place.icon as string,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25),
};
// Create a marker for each place.
markers.push(
new google.maps.Marker({
map,
icon,
title: place.name,
position: place.geometry.location,
})
);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
这是一些来自谷歌地图API的代码。它编译和运行都很好。
问题是,当linter检查它时,它会给我这个错误:222:22 error 'google' is not defined no-undef
我将const google = window.google;
添加到代码的顶部,正如这个答案所解释的那样。在react应用中没有使用create-react-app
来定义Google但这只对使用'new'关键字的实例有帮助。
对于let markers: google.maps.Marker[] = [];
这种情况没有帮助,其中类型被分配给变量
使用eslint,你可以配置全局的。https://eslint.org/docs/user-guide/configuring/language-options specifying-globals
{
"globals": {
"google": "readonly"
}
}