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

相关推荐
小马哥编程15 分钟前
Function.prototype和Object.prototype 的区别
javascript
小白学前端66616 分钟前
React Router 深入指南:从入门到进阶
前端·react.js·react
java1234_小锋23 分钟前
MyBatis如何处理延迟加载?
java·开发语言
web1309332039836 分钟前
前端下载后端文件流,文件可以下载,但是打不开,显示“文件已损坏”的问题分析与解决方案
前端
王小王和他的小伙伴39 分钟前
解决 vue3 中 echarts图表在el-dialog中显示问题
javascript·vue.js·echarts
FeboReigns41 分钟前
C++简明教程(10)(初识类)
c语言·开发语言·c++
学前端的小朱42 分钟前
处理字体图标、js、html及其他资源
开发语言·javascript·webpack·html·打包工具
outstanding木槿1 小时前
react+antd的Table组件编辑单元格
前端·javascript·react.js·前端框架
好名字08211 小时前
前端取Content-Disposition中的filename字段与解码(vue)
前端·javascript·vue.js·前端框架
摇光932 小时前
js高阶-async与事件循环
开发语言·javascript·事件循环·宏任务·微任务