項目中用到了自動定位獲取當前的位置的功能,引入高德地圖中的定位和使用微信JS-SDK中的定位功能,具體代碼以下:javascript
created() {
VueAMap.initAMapApiLoader({
// 高德的key
key: '本身申請的ID',
// 插件集合
plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.Geocoder', 'AMap.Geolocation'],
// 高德 sdk 版本,默認爲 1.4.4
v: '1.4.4'
})
},
複製代碼
var map = new AMap.Map('container', {
resizeEnable: true
})
const self = this
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默認:true
timeout: 5000, // 超過10秒後中止定位,默認:5s
buttonPosition: 'RB', // 定位按鈕的停靠位置
buttonOffset: new AMap.Pixel(10, 20), // 定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
zoomToAccuracy: true // 定位成功後是否自動調整地圖視野到定位點
})
geolocation.getCurrentPosition((status, result) => {
console.log(status, result)
複製代碼
if (result && result.position) {
AMap.plugin('AMap.Geocoder', function() {
var geocoder = new AMap.Geocoder({
city: '010'
})
geocoder.getAddress([result.position.lng, result.position.lat], function(status, result) {
if (status === 'complete' && result.info === 'OK') {
self.isLoading = false
self.data ={
...self.data,
province: result.regeocode.addressComponent.province,
city: result.regeocode.addressComponent.city,
county: result.regeocode.addressComponent.district,
area_code: result.regeocode.addressComponent.adcode
}
}
})
})
複製代碼
wx.getLocation({
type: 'gcj02',
success: (res) => {
if (res.longitude && res.latitude) {
AMap.plugin('AMap.Geocoder', function() {
var geocoder = new AMap.Geocoder({
city: '010'
})
geocoder.getAddress([res.longitude, res.latitude], function(status, result) {
複製代碼
返回的longitude和latitude就是經緯度,而後調用高德地圖經緯度轉化爲具體的方法。vue
第一次寫,沒有經驗。但願能夠你們不吝賜教,謝謝!java