我正在使用 Google Geolocation API 在客户端获取用户位置,并尝试将其传递到服务器端以执行位置查询。
我无法在服务器端获取用户位置/pos 变量(纬度、经度),因为只有在用户接受使用其当前位置(以下是一个实例)后,该值才会分配给输入变量(位置)来自服务器的“GET”方法,反之亦然。
我真的很感激一些从客户端到服务器端获取经纬度的帮助。
下面是我在 geolocation.html 中使用的表单
<form id = "geolocation" action="" method="GET">
<input type="text" id = "location" name="location" value="">
<input type="submit" />
</form>
这是a link到 Google 地理定位 API。 下面是获取用户地理位置的代码摘录,并将其分配给 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
最佳答案
您必须添加成功/错误回调,以便在用户接受共享其位置时触发事件:
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
}
关于javascript - 将用户地理位置从客户端传递到服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18538464/