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

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

  1. index.html引入百度地图js
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&type=webgl&ak=xxxxxxwMprS7jIfPt354VdgP"></script>
  1. 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 = 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. 后台代码
  @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. 配置类
upload:
  url: H:/GoTionBackends/TongJiYuanYuZhou/2023/resources
  path: /u/cms/www/
  outPath: H:/GoTionBackends/TongJiYuanYuZhou/2023/resources/doc
  1. 工具类
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();
        }
    }
}
  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现百度地图关键字检索并自定义结果列表,可以按照以下步骤进行: 1. 引入百度地图 JavaScript API,并加载地图。 2. 在页面中添加一个输入框和一个按钮,用于输入关键字和触发检索。 3. 在按钮的点击事件中,调用百度地图关键字检索服务,传入关键字和检索回调函数。 4. 在检索回调函数中,获取检索结果,并根据需要自定义结果列表。 下面是具体实现步骤: 1. 引入百度地图 JavaScript API,并加载地图。 ```html <!-- 加载百度地图 JavaScript API --> <script src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script> <!-- 创建一个地图容器 --> <div id="mapContainer"></div> <script> // 初始化地图 var map = new BMap.Map("mapContainer"); // 设置地图中心点和缩放级别 var point = new BMap.Point(116.404, 39.915); map.centerAndZoom(point, 15); </script> ``` 2. 添加输入框和按钮。 ```html <!-- 添加输入框和按钮 --> <input type="text" id="keywordInput"> <button onclick="search()">搜索</button> ``` 3. 调用百度地图关键字检索服务。 ```javascript function search() { // 获取输入框的值作为关键字 var keyword = document.getElementById("keywordInput").value; // 创建一个关键字检索服务实例 var local = new BMap.LocalSearch(map, { renderOptions: { map: map } }); // 搜索指定关键字 local.search(keyword, function(results) { // 获取检索结果 var pois = results ? results.getPoi(0) : null; // 根据需要自定义结果列表 if (pois) { var name = pois.title; var address = pois.address; var phone = pois.phone; // TODO: 在页面上显示自定义的结果列表 } }); } ``` 在检索回调函数中,我们首先获取检索结果,然后根据需要自定义结果列表。可以将检索结果中的名称、地址、电话等信息显示在页面上,也可以使用自己的样式和布局来展示检索结果。 这样,就可以实现百度地图关键字检索并自定义结果列表的功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值