Reaction中的Bing地图组件 [英] Bing Map component in React

查看:29
本文介绍了Reaction中的Bing地图组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建组件使用TypeScript在React.js中显示Bing地图。
我知道GitHub中有非常多的组件用于此目的。但我想为自己从头创建此组件。
我在Reaction和componentWillMount函数中创建了类,将脚本标记注入到我的html:

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);
    }

当我想先创建地图,然后再创建this documentcomponentDidMount函数中如下所示:

componentDidMount() {
        var map = new Microsoft.Maps.Map(this.mapElement);
    }

我收到此错误:

找不到名称"Microsoft"。

如何将"Microsoft"模块导入我的组件?

推荐答案

这是Reaction BingMap组件的最低限度实现,不依赖于BingMap类型定义。

首先介绍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--"
    }}
/>

Here is a demo

这篇关于Reaction中的Bing地图组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆