如何通过@ google / maps获取有效地址?

时间:2019-01-25 06:58:49

标签: node.js google-maps google-maps-api-3

在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"],表示地址有效

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

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

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

当然可以按location_typetypes过滤结果,但是如果可以在@types/googlemaps AutoComplete中找到地址,我真的想将其视为有效。这就是我在UI(角度)中使用的内容:

"@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']中仅将其定义为AutoComplete,也可以在"types":["street_address"]中将其定义为"types":["premise"]"@google/maps"。 那么如何使Node.js仅返回在AutoComplete中可以找到的地址?

1 个答案:

答案 0 :(得分:1)

@google/maps库也支持Places API,因此可以这样实现:

//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参数来返回地点详细信息