uniappH5使用高德模糊搜索+跳转到高德H5地图

262 阅读1分钟

跨域配置

// 跨域解决方案
import {
	defineConfig
} from 'vite'
import uni from '@dcloudio/vite-plugin-uni'

export default defineConfig({
	plugins: [
		uni()
	],
	server: {
		port: 3000,
		proxy: {
			'/api': {
				target: 'https://restapi.amap.com', // 目标服务  
				changeOrigin: true,
				rewrite: path => path.replace(/^\/api/, ''),
			}
		}
	}
})

main.js配置

// main.js配置
import App from './App'

import {
	createSSRApp
} from 'vue';
import * as Pinia from 'pinia';

export function createApp() {
	const app = createSSRApp(App);
	app.use(Pinia.createPinia());
	return {
		app,
		Pinia, // 此处必须将 Pinia 返回
	};
}

状态管理pinia配置

// 状态管理pinia配置

import {
	defineStore
} from 'pinia';

import {
	ref,
	reactive
} from 'vue'

export const useCounterStore = defineStore('counter', () => {



	// 地址的外部链接
	const url = ref("")

	const changeUrl = (v) => {
		url.value = v
	}




	return {
		url,
		changeUrl
	};
});

搜索页

这里使用了axios发送请求 需要先在项目中yarn add axios

<!-- 搜索页面 -->
<template>
	<view class="content">


		<input class="addressInput" type="text" v-model="keyword" @input='search' />


		<view class="locationList" v-show="locationList.length>0">
			<view class="location" v-for="(v,i) in locationList" @click="goAutonavi(v.
location)">
				{{v.formatted_address}}
			</view>
		</view>
	</view>
</template>

<script setup>
	import axios from 'axios'
	import {
		reactive,
		ref
	} from 'vue';
	// 初始化pinia
	import {
		useCounterStore
	} from '@/stores/counter'
	const counter = useCounterStore()




	// 定义搜索关键词
	const keyword = ref("")
	// 定义搜索得到的目标数组
	const locationList = reactive([])



	// 点击搜索事件
	const search = async () => {
		// 搜索前先将之前的搜索记录置空
		locationList.length = 0

		let res = await axios.get(
			`https://restapi.amap.com/v3/geocode/geo?address=${keyword.value}&output=XML&key=3927ce10cb3fe3bb137df1ac25c6547f&output=JSON`
		)

		// 搜索到结果展示
		if (res.data.status == 1) {
			locationList.push(...res.data.geocodes)
		}
	}


	// 点击地点跳转事件
	const goAutonavi = (v) => {
		const url =
			`https://uri.amap.com/marker?position=${v}`

		counter.changeUrl(url)

		uni.navigateTo({
			url: '/pages/webview/webview',
		});
	}
</script>

<style>
	.content {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;



		.addressInput {
			width: 90%;
			height: 80rpx;
			border: 1px solid;

		}




		.locationList {
			width: 90%;
			border: 1px solid;


			.location {
				margin: 20rpx 0rpx;
			}
		}

	}
</style>

跳转页

<!-- 跳转页面 -->
<template>
	<view>
		<web-view :src="counter.url"></web-view>
	</view>
</template>

<script setup>
	import {
		useCounterStore
	} from '@/stores/counter'

	const counter = useCounterStore()
	console.log(counter.url);
</script>

<style>

</style>