腾讯地图

QQ 地图库

<script src="//map.qq.com/api/js?v=2.exp&key=[开发者个人密钥]"></script>
1

热力图库

如果要使用默认热力图组件,需要额外引入热力图库

<script src="http://open.map.qq.com/apifiles/plugins/heatmap/heatmap.min.js"></script>
1

安装 npm 包

yarn add react-tmap
yarn add react-loadable
1
2

组件封装

import React, { PureComponent } from "react";
import Loadable from "react-loadable";

const getLocalCity = function() {
  return new Promise(resolve => {
    const CityService = new window.qq.maps.CityService({
      complete: result => resolve(result)
    });

    CityService.searchLocalCity();
  });
};

const TMap = Loadable({
  loader: () => import("react-tmap"),
  loading: () => <div>loading...</div>,
  render: (loaded, props) => {
    const { QMap, Marker } = loaded;
    const { center, onDragend, ...restProps } = props;
    return (
      <QMap
        apiKey="DSABZ"
        center={center}
        events={{
          dragend: event => onDragend(event, loaded.utils)
        }}
        {...restProps}
      >
        <Marker position={center} />
      </QMap>
    );
  }
});

export default class App extends PureComponent {
  state = {
    center: {
      lat: 0,
      lng: 0
    },
    address: ""
  };

  componentDidMount() {
    getLocalCity().then(result => {
      const { latLng, name } = result.detail;
      this.setState({ center: latLng, address: name });
    });
  }

  handleDragend = (event, utils) => {
    utils.getAddressByLatLng(event.center).then(result => {
      const { location, address } = result.detail;
      this.setState({ center: location, address: address });
    });
  };

  render() {
    const { center, address } = this.state;
    return (
      <div>
        <div>{address}</div>
        <TMap zoom={14} center={center} onDragend={this.handleDragend} />
      </div>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  • utils: react-tmap 封装的一些工具函数
  • events: [ 'click', 'dblclick', 'rightclick', 'mouseover', 'mouseout', 'mousemove', 'drag', 'dragstart', 'dragend', 'longpress', 'bounds_changed', 'center_changed', 'zoom_changed', 'maptypeid_changed', 'projection_changed', ['idle', true], 'tilesloaded', 'resize' ]

工具封装

根据 ip 获取城市

const getLocalCity = function() {
  return new Promise((resolve, reject) => {
    const CityService = new window.qq.maps.CityService({
      complete: reject,
      error: reject
    });

    CityService.searchLocalCity();
  });
};
1
2
3
4
5
6
7
8
9
10

根据地址获取位置信息

const getPositionByAddress = address => {
  return new Promise((resolve, reject) => {
    const Geocoder = new window.qq.maps.Geocoder({
      complete: resolve,
      error: reject
    });

    Geocoder.getLocation(address);
  });
};
1
2
3
4
5
6
7
8
9
10

根据官网 api 文档封装更多工具

资源

  • react-tmap
  • [腾讯位置服务]](https://lbs.qq.com/index.html)
上次更新: 11/6/2019, 11:36:02 AM