当前位置: 首页 > news >正文

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 = 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// _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,25var 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.$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/resourcespath: /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();}}
}
http://www.lryc.cn/news/323515.html

相关文章:

  • Java中的Stream流
  • 前端UI怎么防止用户反复提交?
  • OpenHarmony游戏应用程序-实现的一个手柄游戏
  • Redis+Lua脚本+SpringAOP实现接口限流
  • 【wpf应用8】如何让WPF Grid控件根据屏幕尺寸自动调整
  • 掌握ChatGPT:如何用AI撰写高质量论文
  • 平衡隐私与效率,Partisia Blockchain 解锁数字安全新时代
  • 【JavaScript】NPM常用指令指南
  • k8s-多容器Pod、容器保护策略、宽限期、最大生命周期、嵌入式脚本、多容器Pod、资源监控工具
  • 机器学习——线性回归(头歌实训)
  • Echarts 利用多X轴实现未来15天天气预报
  • [数据结构初阶]二叉树
  • matlab和stm32的安装环境。能要求与时俱进吗,en.stm32cubeprg-win64_v2-6-0.zip下载太慢了
  • Opencv面试题
  • Python连接MariaDB数据库
  • 基于python+vue的ITS 信息平台的设计与实现flask-django-nodejs-php
  • MediatR 框架使用FluentValidation对Comand/Query进行自动拦截验证
  • TS + Vue3 elementUI 表格列表中如何方便的标识不同类型的内容,颜色区分 enum
  • 从零开始一步一步掌握大语言模型---(2-什么是Token?)
  • 使用专属浏览器在国内直连GPT教程
  • Wireshark 抓包工具与长ping工具pinginfoview使用,安装包
  • 分享Pandas 数据分析实战课程
  • 26. 删除有序数组中的重复项 (Swift版本)
  • python学生作业管理系统flask-django-nodejs-php
  • 蓝桥杯第二天刷真题
  • RK3568 安装jupyter和jupyterlab
  • 简易指南:国内ip切换手机软件怎么弄
  • Git学习笔记之Git 别名
  • 网络安全笔记-day6,NTFS安全权限
  • 云计算系统等保测评对象和指标选取