【问题标题】:Geocode : converting doesn't work by submitting form地理编码:通过提交表单转换不起作用
【发布时间】:2015-04-16 22:18:13
【问题描述】:

我有一个表单,它使用 onsubmit 属性通过 Google Map API 将地址转换为地理编码。因为我知道地理编码是异步的。有时它有效,有时则无效。任何人都可以帮助我吗? 非常感谢!

jsp 文件:

<body>
    <form name="addLocation" method="POST" action="addLocation.htm" commandName="location" onsubmit="changeAdress()">
        <table>
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" value="${location.name}"/></td>
            </tr>
            <tr>
                <td>Adress</td>
                <td><input type="text" id="adress" name="adress"/></td>
            </tr>
            <tr>
                <td><input type="hidden" id="geolocation" name="geolocation"/></td>
            </tr>
        </table>
            <input type="hidden" name="id" value="${location.id}"/>
            <input type="submit" name="action" value="Save"/>
            <input type="submit" name="action" value="Cancel"/>
    </form>
</body> 

脚本:

    function changeAdress() {
        var adress = document.getElementById("adress").value; 
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': adress}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                document.addLocation.geolocation.value = latitude + " " + longitude;
                document.addLocation.submit();
            } else alert("geocode failed:" + status);
        });
        return false;
    }

你可以自己尝试一下:http://jbossewss-leuvenspeaks.rhcloud.com/Test/newLocation.htm

【问题讨论】:

    标签: javascript jsp google-maps-api-3 geolocation geocode


    【解决方案1】:

    删除内联事件处理程序,使用适当的事件处理程序,然后阻止表单提交,并在地理编码器完成并将值添加到表单时以编程方式提交。

    代码中的return false 不会阻止表单提交。

    document.getElementsByName('addLocation')[0].addEventListener('submit', function(e) {
        e.preventDefault();
    
        var self     = this;
        var adress   = document.getElementById("adress").value; 
        var geocoder = new google.maps.Geocoder();
        var geoloc   = document.getElementById("geolocation"); 
    
        geocoder.geocode({'address': adress}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude  = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
    
                geoloc.value = latitude + " " + longitude;
                self.submit();
            } else {
                alert("geocode failed:" + status);
            }
        }); 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多