reactjs - React 中的 Bing 地图组件
问题描述
我想创建组件以使用 TypeScript 在 React.js 中显示 bing 地图。
我知道 github 中有很多组件用于此目的。但我想为自己从头开始创建这个组件。我在我的 html
的 react 和componentWillMount
函数注入脚本标记中创建了类:head
componentWillMount() {
const script = document.createElement("script");
var scriptURL = "<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=" + this.props.apiKey + "' ></script>";
const scriptText = document.createTextNode(scriptURL);
script.appendChild(scriptText);
document.head.appendChild(script);
}
当我想在这样的功能中创建地图后跟此文档componentDidMount
时:
componentDidMount() {
var map = new Microsoft.Maps.Map(this.mapElement);
}
我收到此错误:
找不到名称“Microsoft”。
我应该如何将“Microsoft”模块导入我的组件?
解决方案
这是 React BingMaps 组件的极简实现,不依赖于 BingMaps 类型定义。
首先介绍一个加载 BingMaps API 和Microsoft
类型的服务:
export interface MapWindow extends Window {
Microsoft: any;
}
declare let window: MapWindow;
export let Microsoft: any;
export function loadBingApi(key?: string): Promise<void> {
const callbackName = "bingAPIReady";
let url = `https://www.bing.com/api/maps/mapcontrol?callback=${callbackName}`;
if (key) {
url += `&key=${key}`;
}
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.defer = true;
script.src = url;
window[callbackName] = () => {
Microsoft = window.Microsoft;
resolve();
};
script.onerror = (error: Event) => {
reject(error);
};
document.body.appendChild(script);
});
}
这是一个接受 mapOptions 作为道具的 Map 组件:
interface IMapProps {
mapOptions?: any;
}
export default class BingMap extends React.Component<IMapProps, any> {
private mapRef = React.createRef<HTMLDivElement>();
public componentDidMount() {
loadBingApi().then(() => {
this.initMap();
});
}
public render() {
return <div ref={this.mapRef} className="map" />;
}
private initMap() {
const map = new Microsoft.Maps.Map(this.mapRef.current);
if (this.props.mapOptions) {
map.setOptions(this.props.mapOptions);
}
return map;
}
}
用法
<BingMap
mapOptions={{
center: [47.60357, -122.32945],
credentials:
"--BingMaps key goes here--"
}}
/>
推荐阅读
- react-native - 如何使 ListHeaderComponent 的一部分粘在 React Native FlatList 上
- javascript - 使用传单搜索显示两次标记
- tableau-api - Tableau 巨大的 if else 条件计算导致请求大小超过解析器限制 1048500 字节
- azure - Azure App Service VNET 集成和网络优化
- java - 减少 Spring Boot 中的 JSON 响应
- python - pygame.display.update(); pygame.error:视频系统未初始化
- python - GCP us-east4 中对等方的间歇性 104 连接重置
- reactjs - ReactJs:是否可以在其他组件的 return() 中包含一个组件 '/posts/[id].tsx?
- javascript - *已修复 *JavaScript 图像压缩器不适用于某些图像 - 所有使用的图像都是 .jpg
- java - 如何检查 JavaFX 中两个 ImageView 对象之间的冲突