首页 > 解决方案 > 如何通过@google/maps 获取有效地址?

问题描述

在 Node.js 微服务中,我正在使用:

"@google/maps": "^0.5.5"

googleMapsClient.geocode({address: '160 Market St, Paterson, NJ 07505'})
    .asPromise()
    .then((response) => {
        console.log("result: " + JSON.stringify(response.json));
    })
    .catch((err) => {
        console.log("error: " + err);
    });

作为回应,我得到:"location_type":"ROOFTOP""types":["street_address"]意味着地址是有效的

如果我尝试验证相同的地址但状态无效,例如“否”,它仍然返回"location_type":"ROOFTOP"and "types":["street_address"]。假设因为谷歌 API 格式化了它可以在响应中看到:

"formatted_address":"160 Market St, Paterson, NJ 07505, USA"

有时 google API 返回"location_type":"ROOFTOP""types":["premise"]

location_type当然,我可以通过and过滤结果,types但我真的想将地址视为有效,如果它可以在@types/googlemaps AutoComplete. 这是我在 UI(Angular)中使用的:

"@types/googlemaps": "3.30.16"
const autocomplete = new google.maps.places.Autocomplete(e.target, {
    types: ['address']
});

var place = google.maps.places.PlaceResult = autocomplete.getPlace();

即使它只是定义为types: ['address']in ,它也AutoComplete可以在. 中找到。 那么如何让 Node.js 只返回可以在 AutoComplete 中找到的地址呢?"types":["street_address"]"types":["premise"]"@google/maps"

标签: node.jsgoogle-mapsgoogle-maps-api-3

解决方案


由于库也支持Places API@google/maps,因此可以这样完成:

//1. query predictions
googleMapsClient.placesQueryAutoComplete(
  {
    input: "160 Market St, Paterson, NJ 07505"
  },
  function(err, response) {
    if (!err) {
      if (response.json.predictions.length === 0) {
        console.log("Place not found");
      } else {
        var prediction = response.json.predictions[0]; //select first prediction
        //2. query place by prediction
        googleMapsClient.place(
          {
            placeid: prediction.place_id
          },
          function(err, response) {
            if (!err) {
              console.log(response.json.result); //prinat place
            }
          }
        );
      }
    }
  }
);

解释:

  • placesQueryAutoComplete首先使用函数返回基于查询的查询预测数组
  • place函数通过提供placeId从先前响应中提取的参数来返回地点详细信息

推荐阅读