谷歌地图地理编码两种方式请求返回地址

本文介绍了如何在谷歌账号中启用Geocoding API,并通过两种方式(直接引入和使用ajax请求)在JavaScript中实现地址的地理编码和反编码。示例代码展示了如何获取并使用返回的地址信息。此外,还提供了错误处理和地址显示的语言设置选项。

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

首先到谷歌账号中启用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值