【问题标题】:Address validation using Google Maps - Check Address使用谷歌地图验证地址 - 检查地址
【发布时间】:2017-12-25 04:46:57
【问题描述】:

我允许用户使用 Google 地图在他们的帖子中添加地址。

如果用户没有为地图输入任何内容或输入奇怪的特殊字符 (#$!@#),它会使网站崩溃并给我这个错误:

var lat = data.results[0].geometry.location.lat;
                  ^
TypeError: Cannot read property 'results' of undefined

我正在尝试找出一种在提交表单时检查此错误的方法。到目前为止,我的运气为零。是否可以检查此错误?

我见过这样的代码,但一切都是未定义的,我不确定在这种情况下如何定义它,坦率地说,我不确定下面的代码是如何运行的。

  if (status == google.maps.GeocoderStatus.OK) {
        var lat = results[0].geometry.location.lat();
        var lon = results[0].geometry.location.lng();
        searchStores(lat, lon);
    } else {
        $addressErrorP.removeClass('hide');
    }

感谢您的帮助!

【问题讨论】:

    标签: google-maps validation google-maps-api-3 error-handling maps


    【解决方案1】:

    想通了:简单而完美。

    第 1 步:确保这在您的页面上。

    <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
    

    然后

    $('#checkingAddress').click(checkGeocode)
    
    function checkGeocode() {
      var addr = document.getElementById('location')
      // Get geocoder instance
      var geocoder = new google.maps.Geocoder()
    
      // Geocode the address
      geocoder.geocode({ address: addr.value }, function (results, status) {
        if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
          alert('looks good')
          // set it to the correct, formatted address if it's valid
          addr.value = results[0].formatted_address
    
          // show an error if it's not
        } else alert('Invalid address')
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 2011-10-22
      相关资源
      最近更新 更多