vue集成百度地图,实现关键字搜索并自定义覆盖物,保存成静态图片

vue集成百度地图,实现关键字搜索并自定义覆盖物

  1. index.html引入百度地图js
javascript 复制代码
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&type=webgl&ak=xxxxxxwMprS7jIfPt354VdgP"></script>
  1. vue页面代码
javascript 复制代码
<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 = BMap
	        this.map = map
	        const that=this
	        var 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 = this
            var myGeo = new this.BMap.Geocoder()
            myGeo.getPoint(queryString, function(point) {
                console.log("point:", point)
                if (point) {
                that.mapLocation.coordinate = point
                that.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 } = item
            this.mapLocation.coordinate = point
            this.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
                // _this.mapCenter = e.point
                })
            }
	    },
        dialogSubmit(formDatas) {
          var _this = this
          //https://api.map.baidu.com/staticimage?center=116.403874,39.914889&width=300&height=200&zoom=11&markers=116.288891,39.914889&markerStyles=-1,https://static.wetab.link/user-avatar/wetab_36.png,-1,23,25
          var 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.resourceUrl
              formDatas.resourceId = data.resource.resourceId
              //_this.$forceUpdate()
              _this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 200,
                  onClose: () => {
                    _this.dialogVisible = false  
                  }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
      },
	}
}
</script>
  1. 后台代码
java 复制代码
  @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);
}
  1. 配置类
java 复制代码
upload:
  url: H:/GoTionBackends/TongJiYuanYuZhou/2023/resources
  path: /u/cms/www/
  outPath: H:/GoTionBackends/TongJiYuanYuZhou/2023/resources/doc
  1. 工具类
java 复制代码
public class HttpClientUtils {
	/**
     * 保存网络图片到本地
     * @param imageUrl 网络地址
     * @param savePath 要保存到的本地地址
     */
    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();
        }
    }
}
相关推荐
轻口味1 小时前
命名空间与模块化概述
开发语言·前端·javascript
前端小小王2 小时前
React Hooks
前端·javascript·react.js
迷途小码农零零发2 小时前
react中使用ResizeObserver来观察元素的size变化
前端·javascript·react.js
娃哈哈哈哈呀2 小时前
vue中的css深度选择器v-deep 配合!important
前端·css·vue.js
旭东怪3 小时前
EasyPoi 使用$fe:模板语法生成Word动态行
java·前端·word
ekskef_sef5 小时前
32岁前端干了8年,是继续做前端开发,还是转其它工作
前端
sunshine6415 小时前
【CSS】实现tag选中对钩样式
前端·css·css3
真滴book理喻5 小时前
Vue(四)
前端·javascript·vue.js
蜜獾云5 小时前
npm淘宝镜像
前端·npm·node.js