vue集成百度地图,实现关键字搜索并自定义覆盖物
index.html
引入百度地图js
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&type=webgl&ak=xxxxxxwMprS7jIfPt354VdgP"></script>
- vue页面代码
<template><div class="app-container"><div><el-autocomplete v-model="mapLocation.address" :fetch-suggestions="querySearch" placeholder="请输入详细地址" style="width: 100%" :trigger-on-focus="false" @select="handleSelect" /></div> <br/><div style="margin: 5px" id="capture" class="capture"><baidu-map id="allmap" :zoom="mapZoom" :center="mapCenter" class="allmap" :scroll-wheel-zoom="true" @ready="handlerBMap"></baidu-map></div><el-button type="primary" @click="dialogSubmit(formData)">确定</el-button></div>
</template>
<script>import BaiduMap from 'vue-baidu-map/components/map/Map.vue'export default {components: {BaiduMap,},data() {return {mapCenter: { lng: 121.508483, lat: 31.289045 },mapLocation: {address: undefined,coordinate: undefined},map: null,BMap: null,formData: {lat: '',lng: '',},}},methods: {handlerBMap({ BMap, map }) {this.BMap = BMapthis.map = mapconst that=thisvar myIcon = new that.BMap.Icon(("../../src/assets/img/biaoqian.png"), new that.BMap.Size(30, 50), {anchor: new that.BMap.Size(30, 50), });const geolocation = new BMap.Geolocation();geolocation.getCurrentPosition(function(r){r.point = {lat: that.formData.lat,lng: that.formData.lng}const mk = new BMap.Marker(r.point, {icon: myIcon});map.addOverlay(mk);map.panTo(r.point);const point = new BMap.Point(r.point.lng,r.point.lat);const gc = new BMap.Geocoder();gc.getLocation(point, function(rs){console.log("rs:", rs)const addComp = rs.addressComponents; const address = rs.address;that.mapLocation.address = rs.address;that.mapInfo.city = addComp.city;});},{enableHighAccuracy: true}) },querySearch(queryString, cb) {var that = thisvar myGeo = new this.BMap.Geocoder()myGeo.getPoint(queryString, function(point) {console.log("point:", point)if (point) {that.mapLocation.coordinate = pointthat.makerCenter(point)} else {that.mapLocation.coordinate = null}}, this.locationCity)var options = {onSearchComplete: function(results) {if (local.getStatus() === 0) {var s = []for (var i = 0; i < results.getCurrentNumPois(); i++) {var x = results.getPoi(i)var item = { value: x.address + x.title, point: x.point }s.push(item)cb(s)}} else {cb()}}}var local = new this.BMap.LocalSearch(this.map, options)local.search(queryString)},handleSelect(item) {var { point } = itemthis.mapLocation.coordinate = pointthis.makerCenter(point)},makerCenter(point) { if (point) {this.mapCenter = point}if (this.map) {var _this = this_this.map.addEventListener('click', function(e) {_this.map.clearOverlays()var myIcon = new _this.BMap.Icon(("../../src/assets/img/biaoqian.png"), new _this.BMap.Size(30, 50), {anchor: new _this.BMap.Size(30, 50), });_this.map.addOverlay(new _this.BMap.Marker(e.point, {icon: myIcon}))_this.formData.lng = e.point.lng_this.formData.lat = e.point.lat})}},dialogSubmit(formDatas) {var _this = thisvar httpurl = "https://api.map.baidu.com/staticimage?";var imgurl = this.$http.adornUrl('/biaoqian.png');var center = formDatas.lng+','+ formDatas.lat;var markerStyles = "-1,"+imgurl+",-1,23,25"var url = httpurl + "center=" + center + "&width=300&height=200&zoom=11&markers=" + center + "&markerStyles=" + markerStyles;this.$http({url: _this.$http.adornUrl(`/resource/url`),method: 'post',data: _this.$http.adornData({url:url})}).then(({data}) => {if (data && data.code === 0) {formDatas.resourceUrl = data.resource.resourceUrlformDatas.resourceId = data.resource.resourceId_this.$message({message: '操作成功',type: 'success',duration: 200,onClose: () => {_this.dialogVisible = false }})} else {this.$message.error(data.msg)}})},}
}
</script>
- 后台代码
@Value("${upload.url}")private String UPLOAD_URL;@Value("${upload.path}")private String UPLOAD_SUFFIX_URL;public String getUPLOAD_URL() {return UPLOAD_URL + getUploadSuffixURL();}public String getUploadSuffixURL() {SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");String dateString = sdf.format(new Date());return UPLOAD_SUFFIX_URL + dateString + "/";}@PostMapping("/url")
public R getUrl(@RequestBody Map<String, String> params) {String url = params.get("url");String suffixUrl = UUID.randomUUID() + ".png";String filePath = this.getUPLOAD_URL();String resourceUrl = this.getUploadSuffixURL() + suffixUrl;if (!new File(filePath).exists()) {new File(filePath).mkdirs();}HttpClientUtils.downloadImage(url, filePath + suffixUrl);SysResourceEntity resource = new SysResourceEntity();resource.setSuffix(".png");resource.setName(suffixUrl);resource.setResourceUrl(resourceUrl);resource.setResourceType(1);resource.setCreateUserId(getUserId());resourceService.save(resource);return new R().put("resource", resource);
}
- 配置类
upload:url: H:/GoTionBackends/TongJiYuanYuZhou/2023/resourcespath: /u/cms/www/outPath: H:/GoTionBackends/TongJiYuanYuZhou/2023/resources/doc
- 工具类
public class HttpClientUtils {public static void downloadImage(String imageUrl, String savePath) {try {URL url = new URL(imageUrl);HttpURLConnection connection = (HttpURLConnection)url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(10*1000);InputStream stream = connection.getInputStream();int len = 0;byte[] test = new byte[1024];BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(savePath));while ((len =stream.read(test)) !=-1){fos.write(test,0,len);}stream.close();fos.close();} catch (Exception e) {e.printStackTrace();}}
}