📌  相关文章
📜  从 google places api 中的邮政编码获取 lat long - Javascript (1)

📅  最后修改于: 2023-12-03 15:06:31.487000             🧑  作者: Mango

从 Google Places API 中的邮政编码获取经纬度 - Javascript

在前端开发中,有时需要使用地理位置信息来对用户进行个性化的提供服务。其中,对于定位精度较不高的场景,我们常常考虑使用用户提供的地址信息来获取其经纬度作为基准点。

较为常用的方案是通过 Google Places API 进行地址解析,获取到邮政编码信息,再通过地理编码(Geocoding)服务获取对应经纬度。下面是获取经纬度的步骤及代码片段。

步骤
  1. 准备 Google Places API Key;

  2. 根据用户提供的地址信息,使用 Places API 完成地址信息解析,获取到目标地址的邮政编码;

  3. 根据邮政编码,使用 Geocoding API 完成地理编码,获取目标地址的经纬度。

代码
const apiKey = 'YOUR_API_KEY';
const address = 'YOUR_ADDRESS';
const url = `https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=${address}&inputtype=textquery&fields=types,formatted_address,name,geometry&key=${apiKey}`;

// 通过地址解析获取邮政编码信息
function geocode() {
  fetch(url)
    .then(response => response.json())
    .then(data => {
      const postalCode = data.candidates[0].formatted_address.match(/\d{5}/)[0];
      console.log(postalCode);
      return geolocate(postalCode);
    })
    .catch(error => console.log(error));
}

// 通过邮政编码获取经纬度信息
function geolocate(postalCode) {
  const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${postalCode}&key=${apiKey}`;
  fetch(url)
    .then(response => response.json())
    .then(data => {
      const lat = data.results[0].geometry.location.lat;
      const lng = data.results[0].geometry.location.lng;
      console.log(`经度:${lng},纬度:${lat}`);
      return { lat, lng };
    })
    .catch(error => console.log(error));
}

geocode();
说明

上面的代码片段包含了两个函数。其中 geocode 函数调用了 Places API 进行地址解析,获取到目标地址的邮政编码信息,并将该信息传递给 geolocate 函数进行地理编码,最终获得经纬度信息。

在地址解析部分,我们设置了查询字段,以便返回查询结果中的相关信息。而在地理编码部分,我们直接使用了邮政编码来获取经纬度。

需要注意的是,上述代码仅供参考,实际使用时,需要根据自己的需求进行适当的修改和调整。另外,地理编码服务需要使用谷歌地图 API Key 来进行身份验证,如果没有有效 API Key 的话,代码将无法正常工作。

以上就是从 Google Places API 中获取经纬度信息的简单介绍,希望能对你有所帮助。