首先到谷歌账号中启用Geocoding API,该API是需要付费的,每个月超过一定的数量来计算。
谷歌地图语言设置:https://malagis.com/google-maps-js-map-display-language.html
1.官网中的方法:
导入script:
https://maps.googleapis.com/maps/api/js?key=youkey&sensor=false&libraries=places&language=en-us"
let address;
const geocoder = new google.maps.Geocoder();
const latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({ location: latlng }).then((res, stauts) => {
console.log(res);
address = res.results[0].formatted_address
});
具体地址按照需求赋值
2.使用ajax请求的方式:
// 谷歌地图地址编码 转换回来的都是英文的
Vue.prototype.getGoogleLocation = function(lat, lon, callback_function) {
// console.log(lat, lon);
var language = "en-us";
const key = "$youkey";
var lang = this.langType;
const failAddr = lang == "en" ? "Fail to parse address" : "地址解析失败";
$.ajax({
type: "get",
async: true,
cache: true,
processData: false,
contentType: false,
timeout: 15000,
url: `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${key}&language=${language}`,
success: function(data) {
try {
console.log(data);
var address = "",
address = data.results[0].formatted_address;//地址
callback_function(address);
} catch (e) {
console.log(e);
callback_function(failAddr);
}
},
});
};
直接在其他组件中使用就行
this.getGoogleLocation (lat,lng,(address)=>{
console.log(address)
})
其他参数参考官网:https://developers.google.cn/maps/documentation/javascript/geocoding