M.R*_*ghi 3 components bing-maps reactjs
我想创建组件以使用 TypeScript 在 React.js 中显示 bing 地图。
我知道github上有很多用于此目的的组件。但我想为自己从头开始创建这个组件。
我在react中创建了类,并在componentWillMount函数中将脚本标记注入到head我的html中:
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);
}
Run Code Online (Sandbox Code Playgroud)
当我想在函数中创建地图后跟此文档componentDidMount时,如下所示:
componentDidMount() {
var map = new Microsoft.Maps.Map(this.mapElement);
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
找不到名称“Microsoft”。
我应该如何将“Microsoft”模块导入到我的组件中?
这是 React BingMaps 组件的极简实现,不依赖于 BingMaps 类型定义。
Microsoft首先介绍加载BingMaps API和类型的服务:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
这是一个接受 mapOptions 作为 props 的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法
<BingMap
mapOptions={{
center: [47.60357, -122.32945],
credentials:
"--BingMaps key goes here--"
}}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6890 次 |
| 最近记录: |