问题: 我有一个带有一些输入字段的表单,我试图在将地址提交到我的控制器之前将其转换为地理编码(使用Spring MVC)。但不知何故,我的地理位置字段在转换后是空的...并且由于某种原因,相同的代码在没有提交的表单上工作。有谁可以帮助我吗?非常感谢!
代码:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="domain.Location"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leuven Speaks</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
</head>
<body>
<jsp:include page="header.jspf"/>
<script type="text/javascript" src="<c:url value="/js/style.js" />"></script>
<form name="addLocation" method="POST" action="addLocation.htm" commandName="location" onsubmit="changeAdress()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Adres</td>
<td><input type="text" id="adress" name="adress"/></td>
</tr>
<tr>
<td><input type="text" 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>
<script type="text/javascript">
function changeAdress(){
var adres = document.getElementById("adress").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': adres}, 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;
}
});
//geolocation is empty...
alert(document.getElementById("geolocation").value);
return true;
}
</script>
</html>
答案 0 :(得分:0)
地理编码是异步的,将表单提交给回调例程。
function changeAdress(){
var adres = document.getElementById("adress").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': adres}, 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;
alert(document.getElementById("geolocation").value);
document.addLocation.submit();
} else alert("geocode failed:"+status);
});
return false;
}