適配h5的時候要使用地圖功能獲取位置,選取了百度地圖。首先在index.html文件引入。javascript
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的key"></script>
以後的實現參考了些資料。具體代碼以下:(這樣就實現了拖動地圖獲取中間的地址信息功能)html
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) }); } };