uniApp使用高德地图api

本文介绍了如何在uniApp中集成高德地图API,包括获取地理位置、调用地图、逆向和正向地理编码以及搜索周边功能。通过引入weixin.js和AMap.js文件,实现了在uniApp项目中使用高德地图API进行导航和地图展示,同时提供了获取经纬度信息并转换为地址描述的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

uniApp使用高德地图api

1,在自己项目中的/src/common/js中的weixin.js写入,没有就新建文件,(具体目录因自己项目而议)

export const weixin = {
/* 获取地理位置接口 */
	getLocation: function (callback) {
		let option = {
			type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
			success: function (res) {
				// var latitude = res.latitude;    // 纬度,浮点数,范围为90 ~ -90
				// var longitude = res.longitude;  // 经度,浮点数,范围为180 ~ -180。
				// var speed = res.speed;          // 速度,以米/每秒计
				// var accuracy = res.accuracy;    // 位置精度
				if (callback && callback instanceof Function) {
					callback(res);
				}
			}
		}
		wx.getLocation(option);
	},
	/* 调起地图 */
	openLocation: function(data){
		wx.openLocation({
		  longitude: Number(data.longitude),
		  latitude: Number(data.latitude),
		  name: data.name,
		  address: data.address
		})
	},
}

2,在自己项目中的/src/common/js中的新建aMap.js文件,(具体目录因自己项目而议)

// <-- 原作者这里使用的是module.exports,在webpack环境下可能会导致一个错误
export const MapLoader = function () {
    return new Promise((resolve, reject) => {
        if (window.AMap) {
            resolve(window.AMap)
        } else {
            var script = document.createElement('script')
            script.type = 'text/javascript'
            script.async = true
            script.src = 'http://webapi.amap.com/maps?v=1.4.8&callback=initAMap&key=你的key值' //key值要去高德api官网申请
            script.onerror = reject
            document.head.appendChild(script)
        }
        window.initAMap = () => {
            resolve(window.AMap)
        }
    })
}

/**
 * 逆向地理编码:将地理坐标(经纬度)转换成地址描述信息
 * 对应为 AMap.Geocoder 的 getAddress 方法
 * @param {Number} longitude 经度
 * @param {Number} latitude  纬度
 */
export const getAddress = function (longitude, latitude) {
    // if (arguments[0] == null || arguments[1] == null) {
    //     longitude = 113.4129
    //     latitude = 23.172686
    // }
    MapLoader().then(AMap => {
        AMap.plugin('AMap.Geocoder', function () {
            var geocoder = new AMap.Geocoder()
            var lnglat = [longitude, latitude]
            geocoder.getAddress(lnglat, function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    // console.log(result)
                    return result
                    // result为对应的地理位置详细信息
                }
            })
        })
    },
        e => { console.log('地图加载失败', e) }
    )
}

/**
 * 正向地理编码:将地址描述信息转换成地理坐标(经纬度),
 * 对应为 AMap.Geocoder 的 getLocation 方法
 * @param {String} site 详细地址
 */
export const getLocation = function (site) {
	return new Promise((resolve)=>{
		MapLoader().then(AMap => {
		    AMap.plugin('AMap.Geocoder', function () {
		        var geocoder = new AMap.Geocoder()
		        geocoder.getLocation(site, function (status, result) {
		            if (status === 'complete' && result.info === 'OK') {
		                // console.log(result,'result')
						resolve(result)
		                // return result
		                // result中对应详细地理坐标信息
		            }
		        })
		    })
		},
		    e => { 
				console.log('地图加载失败', e);
				resolve(false)
			}
		)
	})
}

/**
 * 获取地图周边
 */
export const getCircum = function (newLng,newLat) {
	return new Promise((resolve)=>{
		MapLoader().then(AMap => {
		    AMap.plugin('AMap.Geocoder', function () {
                var map = new AMap.Map("container", {
                    resizeEnable: true
                });
                AMap.service(["AMap.PlaceSearch"], function() {
                    //构造地点查询类
                    var placeSearch = new AMap.PlaceSearch({ 
                        type: '', // 兴趣点类别
                        pageSize: 6, // 单页显示结果条数
                        pageIndex: 1, // 页码
                        city: "", // 兴趣点城市
                        citylimit: false,  //是否强制限制在设置的城市内搜索
                        map: map, // 展现结果的地图实例
                        panel: "panel", // 结果列表将在此容器中进行展示。
                        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
                    });
                    
                    var cpoint = [newLng, newLat]; //中心点坐标
                    // var cpoint = [113.342309, 23.170892]; //中心点坐标
                    placeSearch.searchNearBy('', cpoint, 200);
                    AMap.event.addListener(placeSearch, 'complete', onComplete)
    
                    function onComplete (data) {
                        console.log('定位成功信息')
                    }
                   
                });
		    })
		},
		    e => { 
				console.log('地图加载失败', e);
				resolve(false)
			}
		)
	})
}

3,在要使用到高德的api文件中使用:

//引用
import { getWxOpenId, weixin } from '@/common/js/weixin.js'
import { getLocation } from '@/common/js/AMap.js';

methods: {
        //导航
        openLocation(item, index){
            // console.log(9999, item);
            let that = this;
            getLocation(item).then(res=>{
                // console.log(res);
                if(res && res.geocodes.length >0){
                    let lng = res.geocodes[0].location.lng;
                    let lat = res.geocodes[0].location.lat;
                    if(index == 0) {
                        weixin.openLocation({
                            longitude: lng,
                            latitude: lat,
                            name: res.geocodes[0].formattedAddress,
                            address: res.geocodes[0].formattedAddress
                        })
                    }else{
                    //navigateTo是封装的跳转方法,这里是跳转自己写的地图周边
                        that.navigateTo('./entrepotAmap?lng=' + lng + '&lat=' + lat);
                    }
                }
            });
        },
 }

4,新建放地图周边的vue文件entrepotAmap.vue:(这一步看自己项目需求写,没有可以不管)
html:

<template>
    <view id="entrepotAmap">
        <view class="back" @click="backPage()"></view>
        <view id="container"></view>
        <view id="panel"></view>
    </view>
</template>

js:

<script>
import { getCircum } from '@/common/js/AMap.js';
export default {
    data() {
        return {
            aMapLng: '',
            aMapLat: '',
        }
    },

    mounted() {
    //使用了高德地图api的方法要使用mounted生命周期,使用created页面会显示空白
        this.aMapLng = this.$route.query.lng;
        this.aMapLat = this.$route.query.lat;
        this.getLocation();
    },

    methods: {
       // 获取经纬度信息
        getLocation () {
        // 搜索周边
           getCircum(this.aMapLng,this.aMapLat).then(res=>{
                console.log('');
            });
        },

        // 返回上一页
        backPage() {
            uni.navigateBack({});
        },
    }
}
</script>

css:

<style lang="scss" scoped>
    #entrepotAmap{
        width: 750upx;
        box-sizing: border-box;
        background: #fff;
        height: 100vh;
        overflow: hidden;
        .back {
            position: absolute;
            top: 26upx;
            left: 16upx;
            width: 24upx;
            height: 32upx;
            background: url('../../static/images/home/2.png') no-repeat center /
                100%;
            transform: rotate(180deg);
            z-index: 999;
        }
        #container{
            width: 100%;
            height: 100vh;
        }
        #panel {
            position: absolute;
            background-color: white;
            max-height: 35%;
            overflow-y: auto;
            top: 10upx;
            right: 10upx;
            width: 560upx;
            font-size: 24upx;
        }
    }
</style>
### 实现高德地图导航功能 #### 准备工作 为了在 UniApp 项目中集成高德地图的导航功能,需完成如下准备工作: - 注册成为高德开放平台开发者并获取 API Key[^1]。 ```javascript // 获取API key后的操作可以是保存到项目的配置文件中以便后续调用 const apiKey = 'your_api_key_here'; ``` #### 创建应用与下载 SDK 前往高德开放平台创建新应用,并申请相应的服务权限。对于 H5 和 App 平台而言,应确保选择了适合的地图服务选项。接着按照官方文档指示下载适用于目标环境(如微信小程序、Web 或 Android/iOS 应用)的最新版 SDK 文件[^2]。 #### 页面设置 在希望展示地图或启动导航的位置添加 `<map>` 组件标签,并通过属性绑定来传递必要的参数给该组件实例。这些参数可能包括但不限于中心点坐标(`latitude` `longitude`)、缩放级别(`scale`)以及标记物数组(`markers`)等。 ```html <template> <view> <!-- 地图容器 --> <map id="myMap" class="map" :latitude="latitude" :longitude="longitude" scale="14" :markers="markers" show-location @markertap="handleMarkerTap"> </map> <!-- 导航按钮或其他交互控件可放置于此处 --> <button type="primary" @click="startNavigation">开始导航</button> </view> </template> ``` #### JavaScript 方法定义 编写用于处理用户点击事件的方法,比如当用户点击某个地点时触发导航行为。这里假设已经有一个方法用来初始化地图对象并且绑定了监听器等待用户的输入动作。 ```javascript export default { data() { return { latitude: 39.9087, // 默认纬度 longitude: 116.3975, // 默认经度 markers: [], // 标记列表 }; }, methods: { handleMarkerTap(e) { /* ... */ }, startNavigation(destinationLatlng) { const originLatLng = `${this.latitude},${this.longitude}`; if (process.env.VUE_APP_PLATFORM === 'h5') { window.location.href = `https://uri.amap.com/navigation?from=${originLatLng}&to=${destinationLatlng.join(',')}&mode=car&plugin=AMap.NaviWalk&src=mypage`; } else if (['app-plus', 'app-nvue'].includes(process.env.UNI_PLATFORM)) { plus.maps.Map.openSysMap({ from: new plus.maps.Point(this.longitude, this.latitude), to: new plus.maps.Point(...destinationLatlng.split(',').reverse()), mode: "drive", success: function () {}, fail: function (e) {} }); } } } } ``` 上述代码片段展示了如何根据不同运行环境选择合适的 URL Scheme 来打开系统的默认导航应用程序或者直接利用原生接口发起请求。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值