• react中使用腾讯地图


    腾讯文档

    申请好对应key

    配置限额

    https://lbs.qq.com/service/webService/webServiceGuide/webServiceQuota

    代码

    用到的服务端接口
    1.逆地址解析
    2.关键词输入提示

    import React, { Component } from 'react';
    import styles from './map.less'
    import { Form, Row, Col, Input, Select, Spin, message } from 'antd';
    import PropTypes from 'prop-types';
    import { connect } from 'dva';
    import axios from 'axios'
    import debounce from 'lodash/debounce';
    import createItem from '@/components/form/ItemList/createItem';
    let key = 'your tengxun key';
    
    @createItem()
    @connect((merchantsFile) => ({
      ...merchantsFile,
    }))
    
    export default class mapControl extends Component {
      componentDidMount() {
        // this.props.onRef && this.props.onRef(this);
        this.initMap();
        this.fetchUser = debounce(this.fetchUser, 800);
      }
      static propTypes = {
        editable: PropTypes.bool,
        optionKey: PropTypes.string,
        options: PropTypes.array,
        addBlankOption: PropTypes.bool,
        type: PropTypes.oneOf(['dropdown', 'radio', 'group', 'searchQuery', 'menu']),
        value: PropTypes.any,
        valueType: PropTypes.oneOf(['object', 'array']),
        onChange: PropTypes.func,
        menuData: PropTypes.array,
        term: PropTypes.string,
      }
    
      static defaultProps = {
        dispatch: PropTypes.dispatch,
      }
    
      constructor(props) {
        super(props);
        // this.qqMap = {};
        this.state = {
          inputValue: undefined,
          // 展示中心经纬度和默认Marker经纬度(没啥用)
          center: '',
          fetching: false,
          loading: false,
          lnglatObj: {
            lat: '',
            lng: ''
          },
          data: []
        };
      }
      // 创建TMap方法  核心代码
      TMap = key => {
        return new Promise(function (resolve, reject) {
          window.init = function () {
            resolve(qq);
          };
          var script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = 'http://map.qq.com/api/js?v=2.exp&callback=init&key=' + key;
          script.onerror = reject;
          document.head.appendChild(script);
        });
      }
    
      initMap = () => {
        //设置中心坐标
        this.TMap(key).then(qq => {
          //设置地图属性
          let myOptions = {
            zoom: 16,
            mapTypeId: qq.maps.MapTypeId.ROADMAP,
            viewMode: '2D',
            disableDefaultUI: true
          };
          //创建地图,绑定dom
          this.map = new qq.maps.Map(document.getElementById('myMap'), myOptions);
          // 获取当前位置
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(position => {
              const { latitude, longitude } = position.coords;
              const currentLocation = new qq.maps.LatLng(latitude, longitude);
              this.setMapMarker(currentLocation)
            });
          }
        });
      }
      // 设置地图点位以及将该点位移入中心位置
      setMapMarker = (myLatlng) => {
        // let latObj = { lat: 30, lng: 80 }
        this.map.setCenter(myLatlng);
        //现实已经存在的点 qq已挂载在window下面
        let markerlast = new qq.maps.Marker({
          position: myLatlng,
          map: this.map,
          draggable: true
        });
        qq.maps.event.addListener(markerlast, 'dragend', this.changeAddress);
      }
      // 拖曳点位并且获取地址 逆地址编码
      changeAddress = (location) => {
        this.setState({ loading: true })
        // 根据拖曳的坐标调取接口获取位置
        const { dispatch } = this.props
        dispatch({
          type: "后端接口",
          payload: {
            path: 'ws/geocoder/v1/',
            method: 'GET',
            param: {
              location: location.latLng.lat + ',' + location.latLng.lng,
            }
          }
        }).then(res => {
          this.setState({ loading: false })
          if (res.code !== 20000) {
            message.error(res.data.message);
            return
          } else {
            this.setState({ lnglatObj: res.data.result.location })
            this.setInputValue(res.data.result.address)
          }
        });
      }
    
      handleChange = (chageValue, twoValue) => {
        const { form } = this.props
        const { children, data } = twoValue.props
        this.setState({
          inputValue: children,
          lnglatObj: data.location
        }, () => {
          // console.log(this.state.lnglatObj, 'lnglatObj')
          const { lat, lng } = data.location
          const locationObj = new qq.maps.LatLng(lat, lng)
          this.setValueFather()
          // 地图点位联动
          this.setMapMarker(locationObj)
        })
      }
    
      // 触发父组件赋值
      setValueFather = () => {
        const { inputValue, lnglatObj } = this.state
        this.props.onChange(
          (!inputValue && !lnglatObj)
            ? undefined
            : [inputValue && inputValue.valueOf(), lnglatObj && lnglatObj.valueOf()]
        );
      }
    
      setInputValue = (e) => {
        // 当输入框值为空清空经纬度和默认地址
        if (!e) {
          this.setState({
            lnglatObj: { lng: null, lat: null },
          })
        }
        this.setState({
          inputValue: e,
        }, () => {
          this.setValueFather()
        })
      }
      // 获取模糊查询
      fetchUser = value => {
        const { dispatch } = this.props
        this.setState({ loading: true })
        dispatch({
          type: "后端接口",
          payload: {
            enableCache: true,
            path: 'ws/place/v1/suggestion',
            method: 'GET',
            param: {
              keyword: value
            }
          }
        }).then(res => {
          this.setState({ loading: false })
          if (res.code === 20000) {
            message.success(res.message);
            this.setState({ data: res.data.data });
          } else {
            message.error(res.message);
          }
        });
      };
      render() {
        const { inputValue, fetching, data, loading } = this.state
        const { valueMap } = this.props
        const options = this.state.data.map(d => <Option key={d.id} data={d}>{d.address}</Option>);
        return (<>
          <Select
            showSearch
            {...this.props}
            value={inputValue ? inputValue : valueMap}
            placeholder='请输入详细地址'
            filterOption={false}
            onSearch={this.fetchUser}
            onChange={this.handleChange}
            notFoundContent={fetching ? <Spin size="small" /> : null}
            style={{ marginBottom: 16, width: '100%' }}
            loading={loading}
          >
            {options}
          </Select>
          <div id="myMap" className={styles.myMap}></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
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215

    map.less

    .myMap {
      /*地图(容器)显示大小*/
      width: 100%;
      height: 215px;
    }
    
    .rowmap {
      margin-bottom: 24px;
    }
    
    .mapcon {
      height: 215px;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    跨语言深入探讨如何实现方法增强:Java & Go的多策略实现
    web前端期末大作业 基于HTML+CSS+JavaScript绿色的在线教育平台网站响应式企业网站模板
    java毕业设计毕业设计管理系统Mybatis+系统+数据库+调试部署
    maven工具的配置和使用
    面试准备-中文面试问答(非技术)
    CVPR2022 | 可精简域适应
    pdf怎么转换成jpg图片?
    基于Basic auth 的一个C# 示例
    Mysql使用中的性能优化——索引对插入操作的性能影响
    jmeter 解决查看结果树响应内容中文乱码问题
  • 原文地址:https://blog.csdn.net/LRQQHM/article/details/136745628