首页 > 解决方案 > 当仅使用单字符、双字符或 rand 字符时,防止 google geocoder API 返回状态“OK”

问题描述

如果我只向地理编码 api 传递一个“S”,我会得到一个状态为“OK”的结果。输入城市或城镇时,有什么方法可以让状态返回“OK”?这样当用户输入类似的内容时,我就不会得到错误的结果

前任。'S' 或 'SA' 或 'TTT'

this.geocoder = new google.maps.Geocoder();
this.geocoder.geocode({
    address: this.registerForm.get('city').value,
    componentRestrictions: {
      country: 'US'
    }
  },
  (results, status) => {
    // do stuff here.
  });

标签: javascriptgoogle-places-apiangular7google-geocoding-api

解决方案


Geocoding API is not an address validation service. It was never designed for this purpose. The main idea of Geocoding API is providing best match for your input text according to certain criteria. So, it will always try return a result even if input text doesn't have much sense. Unfortunately, there is no way to change this behavior of service.

If you would like your users to send only valid addresses, have a look at autocomplete service (type-ahead-search behavior). This way users will select one of suggested addresses and you can get detailed information for selected place ID (which exists in Google database).

For further details look at the autocomplete documentation: https://developers.google.com/maps/documentation/javascript/places-autocomplete

I hope this helps!


推荐阅读