我做了一个小脚本,它返回经度和latidue到输入形式的值。在HTML中:
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById('latitude').value = position.coords.latitude;
document.getElementById('longitude').value = position.coords.longitude;
}
</script>
<input type="text" id="latitude" />
<input type="text" id="longitude" />
有效。但我想让它在Spring中运行。 我试图这样做:
<p id="demo">Click the button to get your coordinates:</p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById('latitude').value = position.coords.latitude;
document.getElementById('longitude').value = position.coords.longitude;
}
</script>
<form:form method="POST" commandName="geolocation">
<form:input path="latitude" id="latitude" type="text" />
<form:input path="longitude" id="longitude" type="text" />
<input id="bigbutton" type="submit" onclick="getLocation()" value="Confirm" />
</form:form>
但它让我归零。怎么了? 这是我的表单类:
private double latitude;
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
控制器:
@RequestMapping(value = "/about", method = RequestMethod.GET)
public String getAboutPage(Map<String, Object> map,
@ModelAttribute("geolocation") GeoLocation geolocation,
@ModelAttribute("search") SearchForm query, BindingResult result) {
map.put("news", new News());
map.put("newsList", newsService.getAboutPage());
map.put("temp", TEMP);
return "about";
}
@RequestMapping(value = "/about", method = RequestMethod.POST)
public String getAboutPageProcess(Map<String, Object> map,
@ModelAttribute("geolocation") GeoLocation geolocation,
@ModelAttribute("search") SearchForm query, BindingResult result) {
System.out.println(geolocation.getLatitude());
System.out.println(geolocation.getLongitude());
map.put("news", new News());
map.put("newsList", newsService.getAboutPage());
map.put("temp", TEMP);
return "about";
}
答案 0 :(得分:1)
使用onsubmit
并让getLocation
返回false,然后在showPosition
中手动提交表单,或使用jQuery / YUI /某些内容将getLocation
作为非破坏性附加事件处理程序。
编辑:也许是这样的:http://jsfiddle.net/mz6zN/