node.js - 如何通过@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"
解决方案
由于库也支持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
从先前响应中提取的参数来返回地点详细信息
推荐阅读
- sql-server - SQL Server 机器学习服务 - 无法启动运行时。ErrorCode 0x80070032: 50(不支持该请求。)
- java - 使用 Neo4j 的休眠 OGM - 与服务器的应用程序连接失败
- flask - Flask 上 OAuth 的单元测试
- python - 为什么 OpenCV 会创建奇怪的矩形?
- node.js - multer上传带有正文和验证的文件并将文件名保存到数据库
- c++ - 从 csv 文件加载二维数组大小问题
- javascript - jQuery、JSON 实时搜索
- emacs - 如何在遵守`.gitignore`的同时运行递归`dired-maybe-insert-subdir`?
- vue.js - 有没有人将 Dexie 与 localbase 进行比较?
- ubuntu - 使用 Gnuplot 制作多重折线图