我正在使用Google Geolocation API在客户端获取用户位置,并尝试将其传递到服务器端以执行位置查询。
我无法获取用户位置/ pos变量(lat,lng)到服务器端,因为只有在用户接受使用其当前位置(此后是一个实例)后才将此值分配给输入变量(位置)来自服务器的“GET”方法,反之亦然。
我非常感谢从客户端到服务器端获取lat,lng的一些帮助。
以下是我在geolocation.html中使用的表单
<form id = "geolocation" action="" method="GET">
<input type="text" id = "location" name="location" value="">
<input type="submit" />
</form>
这是Google地理位置API的a link。 下面是获取用户地理位置并将其分配给id = location的HTML输入字段的代码的摘录,以便我可以在服务器端使用GET方法来获取地理位置。
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
// the below code has been inserted to assign a JS variable to HTML field called 'location'
document.getElementById('location').value = pos
答案 0 :(得分:0)
当用户同意共享其位置时,您必须添加成功/错误回调以触发事件:
navigator.geolocation.getCurrentPosition(success, error);
function success(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
document.getElementById('location').value = lat + ',' + lon;
}
function error() {
// do something with the error message
}