如何检查地址有效性? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

我写了以下示例:

http://jsfiddle.net/214190tj/1/

HTML:

<label for="searchTextField">Please Insert an address:</label>
<br>
<input id="searchTextField" type="text" size="50">
<input type="submit" value="is valid">

JS:

var input = document.getElementById('searchTextField');
var options = {componentRestrictions: {country: 'us'}};

new google.maps.places.Autocomplete(input, options);

现在它运行良好,但我需要检查按钮点击时uset没有输入类似“dsgfdsgfjhfg”的内容。

请帮助改进我的代码。

附:

这大约是我想要的,但它在回调中执行。我需要一个返回true或false的函数。

function codeEditAddress(id) {
        var address = document.getElementById('address' + id).value;
        isValid = undefined;
        geocoder.geocode({ 'address': address}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                $("#mapLat" + id).val(results[0].geometry.location.lat());
                $("#mapLng" + id).val(results[0].geometry.location.lng());
                if (marker) {
                    marker.setMap(null);
                }
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                marker.setMap(map);
                isValid = true;
            } else {               
                isValid = false;
            }
          });       
    }
javascript google-maps google-maps-api-3 geocoding
1个回答
0
投票

您将不得不重新设计地址检查器功能,以便传入回调函数。从异步操作中返回一个值本身就没有意义。你会想要这样的东西:

function codeEditAddress(id, callback) {
        var address = document.getElementById('address' + id).value;
        geocoder.geocode({ 'address': address}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                $("#mapLat" + id).val(results[0].geometry.location.lat());
                $("#mapLng" + id).val(results[0].geometry.location.lng());
                if (marker) {
                    marker.setMap(null);
                }
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                marker.setMap(map);
                callback(true);
            } else {               
                callback(false);
            }
          });       
    }

要调用此函数:

codeEditAddress(id, function(isValid) {
  if (isValid) {
    // submit form, do whatever
  }
  else {
    // show error message, etc
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.