首页 > 解决方案 > 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”模块导入我的组件?

标签: reactjscomponentsbing-maps

解决方案


这是 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--"
    }}
/>

这是一个演示


推荐阅读