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 小时前
【el-form】记一例好用的el-input输入框回车调接口和el-button按钮防重点击
javascript·vue.js·elementui
我要洋人死1 小时前
导航栏及下拉菜单的实现
前端·css·css3
科技探秘人1 小时前
Chrome与火狐哪个浏览器的隐私追踪功能更好
前端·chrome
科技探秘人1 小时前
Chrome与傲游浏览器性能与功能的深度对比
前端·chrome
JerryXZR1 小时前
前端开发中ES6的技术细节二
前端·javascript·es6
七星静香1 小时前
laravel chunkById 分块查询 使用时的问题
java·前端·laravel
q2498596931 小时前
前端预览word、excel、ppt
前端·word·excel
小华同学ai1 小时前
wflow-web:开源啦 ,高仿钉钉、飞书、企业微信的审批流程设计器,轻松打造属于你的工作流设计器
前端·钉钉·飞书
Gavin_9152 小时前
【JavaScript】模块化开发
前端·javascript·vue.js
懒大王爱吃狼3 小时前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍