vue3使用腾讯地图api搜索地图中所有的学校

<template>
    <div class="map">
        <div class="map-title">周边配套</div>

        <div class="map-main">
            <div class="map-main-map" id="container"></div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import imgSrc1 from '/@/assets/frontend/Union.png'
import imgSrc2 from '/@/assets/frontend/assetAuction/juseditutp.png'
import { jsonp } from 'vue-jsonp'

// 父传子的值,里面有默认点位
const props = defineProps({
    initData: {
        type: Object,
        default: {},
    },
})

const TMap = (window as any).TMap

const center = ref(new TMap.LatLng(39.822349621652, 109.96280795932))

let map: any = null

let markerLayer: any = null

// 新增点位
const addMarkers = (locations: any, center: any, name = '') => {
    if (markerLayer) {

        let geometries = []

        // 如果locations存在,那么才渲染腾讯api的点位
        if (locations) {
            geometries = locations.map((item: any, index: any) => ({
                id: `marker-${index}`,
                styleId: 'school',
                position: new TMap.LatLng(Number(item.location.lat), Number(item.location.lng)),
                content: item.title,
            }));
        }

        // 默认点位
        const defaultCenter = {
            id: 'demo2',
            styleId: 'default',
            position: center,
            content: name,
        }

        geometries = [defaultCenter, ...geometries]

        markerLayer.setGeometries(geometries); // 更新所有标记
    }
};

// 腾讯api
const getMapAround = (position: any, center: any, name = '') => {
    jsonp(`https://apis.map.qq.com/ws/place/v1/search`, {
        key: '2KPBZ-2CMKL-A3ZPD-MH4RL-ZY6H2-RCBXU',
        keyword: encodeURIComponent('学校'),
        boundary: `nearby(${position[0]},${position[1]},1000)`,
        page_size: 20,
        page_index: 1,
        output: 'jsonp',
    }).then((response: any) => {
       
       // 如果调用成功了,传过去,失败就代表api上限了,那么就显示默认
        if (response.data) {
            addMarkers(response.data, center, name);
        } else {
            addMarkers(null, center, name);
        }

    }).catch(function (error: any) {
        console.log("🚀 ~ getMapAround ~ error:", error)
    });

}

const init = () => {
    //定义map变量,调用 TMap.Map() 构造函数创建地图
    map = new TMap.Map(document.getElementById('container'), {
        center: center.value, //设置地图中心点坐标
        zoom: 16, //设置地图缩放级别
        mapStyleId: 'style1', //设置地图样式
    })

    markerLayer = new TMap.MultiMarker({
        id: 'marker-layer',
        map: map,
        styles: {
            default: new TMap.MarkerStyle({
                width: 134, // 宽度
                height: 32, // 高度
                src: imgSrc1,
                color: '#fff', // 标注点文本颜色
                size: 12, // 标注点文本文字大小
                offset: { x: 0, y: -3 },
            }),
            school: new TMap.MarkerStyle({
                width: 32, // 宽度
                height: 32, // 高度
                src: imgSrc2,
                color: '#333', // 标注点文本颜色
                size: 12, // 标注点文本文字大小
                offset: { x: 0, y: 20 },
            }),
        },
    })
}

onMounted(() => {
    init()
})

watch(
    () => props.initData,
    (newVal) => {
        if (newVal?.home?.position) {
            const position = newVal.home.position.split(',')

            if (position.length === 2) {
                center.value = new TMap.LatLng(Number(position[0]), Number(position[1]))
                if (map) {
                    map.setCenter(center.value)
                    getMapAround(position, center.value, newVal?.home?.name)
                }
            }
        }
    },
    { immediate: true }
)
</script>

<style scoped lang="scss">
.map {
    margin-top: 52px;

    .map-title {
        font-weight: 500;
        font-size: 24px;
        color: #333333;
    }

    .map-main {
        margin-top: 16px;
        display: flex;

        .map-main-map {
            width: 100%;
            height: 420px;
        }
    }
}
</style>

### 如何在 Spring Boot 项目中使用腾讯地图 API 要在 Spring Boot 项目中集成并使用腾讯地图 API,主要涉及以下几个方面: #### 准备工作 首先需要注册成为开发者,并获取应用的密钥(Key)。这一步骤对于访问任何第三方服务都是必要的。完成此操作后,在项目的 `application.yml` 或者 `application.properties` 文件里配置好这些参数。 #### 添加依赖项 为了简化 HTTP 请求处理过程以及更好地管理 JSON 数据交换,建议引入像 RestTemplate 这样的工具类库。可以通过修改 Maven 的 POM 文件或 Gradle 构建脚本来添加相应的依赖包[^1]。 ```xml <!-- 对于Maven用户 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 如果还需要JSON支持可选加入Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` #### 创建服务层接口 定义一个用于封装调用腾讯地图 Web Service API 功能的服务组件。这里以地理编码为例展示基本框架结构[^4]: ```java import org.springframework.stereotype.Service; import java.io.IOException; @Service public class TencentMapService { private static final String GEOCODE_URL = "https://apis.map.qq.com/ws/geocoder/v1/"; /** * 获取地址对应的经纬度坐标. */ public Coordinate getCoordinateByAddress(String address, String key) throws IOException { // 组织请求URL... StringBuilder urlBuilder = new StringBuilder(GEOCODE_URL); urlBuilder.append("?address=").append(address).append("&key=").append(key); // 发送GET请求并解析响应数据... return null; // 返回结果对象 } } ``` 请注意上述代码片段仅作为示意用途,实际开发过程中还需考虑异常捕获、超时设置等因素;另外就是具体到不同类型的API调用时,传参方式也会有所区别,请参照官方文档说明进行调整。 #### 控制器实现 最后编写 RESTful 风格控制器以便外部能够触发该功能逻辑: ```java @RestController @RequestMapping("/tencentmap") public class TencentMapController { @Autowired private TencentMapService tencentMapService; @GetMapping("/geocode") public ResponseEntity<?> geocode(@RequestParam String address,@RequestParam String key){ try{ var coordinate=tencentMapService.getCoordinateByAddress(address,key); return ResponseEntity.ok(coordinate); }catch (Exception e){ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); } } } ``` 以上即是在 Spring Boot 应用程序内接入腾讯地图开放平台所提供的部分基础服务的大致流程概述。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值