Taro之使用百度地图

  适配h5的时候要使用地图功能获取位置,选取了百度地图。首先在index.html文件引入。

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的key"></script>

之后的实现参考了些资料。具体代码如下:(这样就实现了拖动地图获取中间的地址信息功能)

componentDidMount = () => {
    const { BMap, BMAP_STATUS_SUCCESS } = window
    let self = this
    map = new BMap.Map("container")
    let poi 
    
    let geolocation = new BMap.Geolocation()
    geolocation.getCurrentPosition(function (r) {
      if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        let mk = new BMap.Marker(r.point);
        getAddress(r.point);
        poi = new BMap.Point(r.longitude, r.latitude)
        map.centerAndZoom(poi, 15)
        map.addOverlay(mk)
        map.panTo(r.point)
        let centerPixel = map.pointToOverlayPixel(map.getCenter())
        map.setCenter(map.overlayPixelToPoint({ x: centerPixel.x, y: centerPixel.y}))
        let mkn
        map.addEventListener('dragend', function () {
          map.removeOverlay(mk)
          map.removeOverlay(mkn)
          let pixel = map.pointToOverlayPixel(map.getCenter());
          let Point = map.overlayPixelToPoint({ x: pixel.x, y: pixel.y});
          mkn = new BMap.Marker(Point);
          getAddress(Point)
          map.addOverlay(mkn);
        })
      } else {
        alert('failed' + this.getStatus());
      }
    })
    function getAddress(point) {
      let gc = new BMap.Geocoder();
      gc.getLocation(point, function (rs) {
        let addComp = rs.addressComponents;
        let address =   addComp.district + addComp.street + addComp.streetNumber;
        console.log(rs);
        realaddress = address
        self.setState({
          address: realaddress
        })
        Taro.setStorageSync('site', realaddress)
      });
    }

  };

猜你喜欢

转载自www.cnblogs.com/all1008/p/10650863.html