地理编码:通过提交表单进行转换并不起作用

时间:2015-04-16 22:18:13

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

我有一个表单,使用onsubmit属性将地址转换为使用Google Map API的地理编码。因为我知道地理编码是异步的。有时候它会起作用,有时却不起作用。有人可以帮我吗? 非常感谢!

jsp-file:

<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

1 个答案:

答案 0 :(得分:0)

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

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

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);
        }
    }); 
});
相关问题