Google Maps JavaScript API Loader地图选位置(uniapp)


myMap.vue

html 复制代码
<template>
	<div class="map">
		<div class="mapStyle">
			<div class="mapRightStyle">
				<div :style="googleMapStyle" class="googleMap" :id="mapID"></div>
			</div>
		</div>

		<mg-input v-model="input" pr="请输入选择地点" class="controls" @input="chnageinput">
			<!-- <i slot="ft" class=" el-icon-search"></i> -->
			<view slot="ft" class="choose" @click="setAddress()">选择</view>
		</mg-input>
		<div class="mapLeftStyle">
			<div class="card" v-if="list.length > 0">
				<!-- <i class="el-icon-location fl mgr10" style="margin-top: 10px"></i> -->
				<div class="item" v-for="(item, index) in list" :key="index">
					<div @click="confirm(item)">
						<div class="title">{{ item.structured_formatting.main_text }}</div>
						<div class="address">
							{{ item.structured_formatting.secondary_text }}
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import {
		Loader
	} from "@googlemaps/js-api-loader"; //引入
	import {
		mapMutations
	} from 'vuex';
	import mgInput from '@/components/form/mg-input.vue';
	// 输入框模糊查询
	let searchBox = undefined;
	// 搜索地点和检索地点详细信息
	let service = undefined;
	// 对请求进行地理编码
	let geocoder = undefined;
	let marker = undefined;

	export default {
		props: {
			//地图id
			mapID: {
				type: String,
				default: () => {
					return "googleMap";
				},
			},
			//谷歌地图样式
			googleMapStyle: {
				type: Object,
				default: () => {
					return {
						wdith: "100%",
						height: "600rpx",
					};
				},
			},
			//谷歌地图配置
			mapOptions: {
				type: Object,
				default: () => {
					return {
						//为了关闭默认控件集,设置地图的disableDefaultUI的属性为true
						disableDefaultUI: false,
						// 启用缩放和平移
						gestureHandling: "greedy",
						panControl: true,
						zoomControl: true,
						scaleControl: true,
						//关闭街景
						streetViewControl: false,
					};
				},
			},
			//谷歌地图缩放级别
			zoom: {
				type: Number,
				default () {
					return 15;
				},
			},
			//谷歌地图图形path
			mapPath: {
				type: String,
				default: () => {
					return "";
				},
			}
		},
		components: {
			mgInput,
		},
		data() {
			return {
				map: {},
				BMap: {},
				input: "",
				googleMapCenter: {
					lng: "",
					lat: "",
				},
				//标记点
				marker: [],
				//图形实例
				graphicalExample: null,
				//图形路径经纬度
				graphicalPath: [],
				apiKey: "AIzaSyBkiTXJFE_cQX37QwgiGhZTxuFwxF4TuXs",
				// 模糊匹配数据
				list: [],
			};
		},
		created() {

		},
		mounted() {
			//通过浏览器的Geolocation API获取经纬度
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(this.showPosition);
			} else {
				console.log("Geolocation is not supported by this browser.");
			}
			this.init();
		},
		methods: {
			setAddress() {
				this.$store.commit('setAddressOnMap', this.input)
				this.$router.go(-1)
			},
			showPosition(position) {
				const latitude = position.coords.latitude;
				const longitude = position.coords.longitude;
				console.log("Latitude: " + latitude);
				console.log("Longitude: " + longitude);
				this.googleMapCenter = {
					lng: longitude,
					lat: latitude,
					// lat:-33.44432,
					// lng:-70.72391
				};
				this.init();
			},
			init() {
				this.$nextTick(() => {
					const loader = new Loader({
						apiKey: this.apiKey, //之前的key
						version: "weekly", //版本
						libraries: ["places", "drawing"], //插件库places为基础库 drawing为绘制工具库
						// region: "Canada",
						// language: "en",
					});
					const mapOptions = {
						center: {
							lat: this.googleMapCenter.lat * 1,
							lng: this.googleMapCenter.lng * 1,
						}, //中心点
						zoom: this.zoom, //缩放级别
						...this.mapOptions, //其他配置
					};
					loader
						.load()
						.then((google) => {
							const map = new google.maps.Map(
								document.getElementById(this.mapID),
								mapOptions
							);
							this.googleMap = map;
							this.googleApi = google;
							// 自动完成请求 参考文档:https://developers.google.com/maps/documentation/javascript/reference/places-autocomplete-service?hl=en
							searchBox = new google.maps.places.AutocompleteService();
							// 搜索地点和检索地点详细信息 参考文档:https://developers.google.com/maps/documentation/javascript/reference/places-service?hl=en
							service = new google.maps.places.PlacesService(map);
							// 对请求进行地理编码 参考文档:https://developers.google.com/maps/documentation/javascript/reference/geocoder?hl=en
							geocoder = new google.maps.Geocoder();
							marker = new google.maps.Marker({
								map: map,
								position: {
									// lat:-33.44432,
									// lng:-70.72391
									lat: this.googleMapCenter.lat,
									lng: this.googleMapCenter.lng
								},
								draggable: true,
							});
							console.log(this.googleMap, "谷歌地图实例");
							console.log(this.googleApi, "谷歌地图api");
						})
						.catch((e) => {
							console.log(e);
						});
				});
			},
			GetMapLocation(results, status) {
				if (status === "OK") {
					console.log(results[0].geometry.location, results[0], results, "查验");
					this.googleMap.setCenter(results[0].geometry.location);
					marker.setPosition(results[0].geometry.location);
				} else {
					console.log("error");
				}
			},
			// 点击一行地址
			confirm(e) {
				// 搜索地点和检索地点详细信息
				service.getDetails({
					placeId: e.place_id
				}, (event, status) => {
					if (status === "OK") {
						console.log(event.name, "===", event);
						this.input = event.name;
						// if (!event.name) return;
						let str = event.name;
						// 对请求进行地理编码
						geocoder.geocode({
							address: str
						}, this.GetMapLocation);
					} else {}
				});
			},
			chnageinput(e) {
				console.log(e);
				searchBox.getPlacePredictions({
					input: e
				}, (event, status) => {
					console.log(event, "===");
					if (status === "OK") {
						this.list = event || [];
						// place_id 后面有用,所以只保留存在place_id的数据
						this.list = this.list.filter((x) => x.place_id);
						console.log(event, "===", this.list);
					} else {
						this.list = [];
					}
				});
			},
		},
	};
</script>
<style lang="scss" scoped>
	.title {
		font-weight: 550;
	}
</style>

使用地图

html 复制代码
<mg-input v-model="params1.address" isr="1" ht="详细地址" htc="c3 f30" pr="" icn="t-r">
					<view slot="ft" class="p-5-15 iconfont icondt f40" @click="enterMap()"></view>
				</mg-input>
js 复制代码
enterMap() {
				this.go({
					t: 1,
					url: '/yb_shd/my/myMap/myMap'
				});
			},

注意:需要开外网 注册谷歌地图的key

相关推荐
远望清一色13 分钟前
基于MATLAB的实现垃圾分类Matlab源码
开发语言·matlab
GIS程序媛—椰子19 分钟前
【Vue 全家桶】7、Vue UI组件库(更新中)
前端·vue.js
confiself23 分钟前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
DogEgg_00125 分钟前
前端八股文(一)HTML 持续更新中。。。
前端·html
ZL不懂前端28 分钟前
Content Security Policy (CSP)
前端·javascript·面试
乐闻x31 分钟前
ESLint 使用教程(一):从零配置 ESLint
javascript·eslint
木舟100932 分钟前
ffmpeg重复回听音频流,时长叠加问题
前端
XiaoLeisj34 分钟前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee
杜杜的man38 分钟前
【go从零单排】go中的结构体struct和method
开发语言·后端·golang
幼儿园老大*38 分钟前
走进 Go 语言基础语法
开发语言·后端·学习·golang·go