Taro小程序中引入腾讯地图与逆编码

389 阅读1分钟
import { CoverView, Map, View } from '@tarojs/components'
import { Component} from "react";
import Taro from "@tarojs/taro";

const normalCallout = {
  id: 1,
  latitude: 32,
  longitude: 122,
  callout: {
    content: '位置',
    color: '#ff0000',
    fontSize: 10,
    borderWidth: 2,
    borderRadius: 10,
    borderColor: '#000000',
    bgColor: '#fff',
    padding: 5,
    display: 'ALWAYS',
    textAlign: 'center',
  }
}

export default class OwnerMap extends Component{
  constructor(props) {
    super(props);
    this.state = {
      longitude:111,//中心经度
      latitude:23,//中心纬度
      customMarkers:[],
      showTarget:false,
    }
  }

  async componentDidMount(){
    await this.getCurrentLocation('init')
  }

  //获取当前位置
  getCurrentLocation = async (e) => {
    const that = this
    if(e !== 'init'){
      e.stopPropagation()
    }
    await Taro.getLocation({
      type: 'wgs84',
      success: function (res) {
        const latitude = res.latitude
        const longitude = res.longitude
        that.setState({
          latitude,
          longitude,
        })
        console.log(res)
      }
    })
  }
  //目标
  onTab = (e)=>{
    const { showTarget } = this.state
    if(showTarget){
      return
    }
    normalCallout['longitude'] = e.currentTarget.longitude
    normalCallout['latitude'] = e.currentTarget.latitude
    this.setState({
      customMarkers:[normalCallout]
    })
    console.log(e)
  }
  componentDidUpdate(prevProps) {
    if(prevProps !== this.props){
      const mapCtx = Taro.createMapContext('myMap')
      mapCtx.moveToLocation()
      this.setState({customMarkers:[]})
    }
  }

  render(){
    const { latitude,longitude,customMarkers } = this.state
    return (
      <Map
        markers={customMarkers.length?customMarkers:[]}
        latitude={latitude}
        longitude={longitude}
        style={{ height: '100vh', width: '100vw' }}
        // showLocation={true}
        onClick={this.onTab}
        // showCompass={true}
        // id="myMap"
      >
      </Map>
    )
  }

}

逆编码

申请逆编码lbs.amap.com/api/webserv…

注册之后

微信小程序无法直接使用fetch发送请求,使用微信APIwx.request()