我对 Javascript 很陌生,遇到了一个我自己无法解决/理解的问题。
假设我使用“userPosition”属性创建了“UserMap”类,并希望使用 Geolocation API 获取坐标。
navigator.geolocation.getCurrentPosition(this.getCoordinates);
然后在回调函数中我得到纬度和经度:
var coords = { "lat" : position.coords.latitude, "lng" : position.coords.longitude };
我的问题是:如何让这个回调函数向 UserMap 实例报告,以便更新 userPosition 属性?显然 this.userPosition = coords;
在这里不起作用。现在我对处理回调感到非常无助。我希望每次从用户那里获得更新的坐标时都不必创建一个新对象。
这是错误的代码:
function UserMap() {
this.map = L.map('map', {"zoomControl" : false});
this.userPosition = {};
this.boundary = {};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(this.getCoordinates);
}
else{ alert("Geolocation is not supported by your browser.");
return false;
}
this.map.on("click", function(e) {
alert("Lat: " + e.latlng.lat + " Lng: " + e.latlng.lng);
});
this.display();
}
UserMap.prototype.getCoordinates = function(position) {
var coords = { "lat" : position.coords.latitude, "lng" : position.coords.longitude};
this.userPosition = coords; // I understand why this line won't work, but can't find a workaround solution
}
UserMap.prototype.display = function() {
var lat = this.userPosition.lat;
var lng = this.userPosition.lng;
this.map.setView([lat, lng], 18);
var tile = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
minZoom: '16',
}).addTo(this.map);
L.marker([lat, lng]).addTo(this.map)
.bindPopup('You are here!')
.openPopup();
}
最佳答案
在回调中,您可以使用 ajax 调用,它将以非阻塞方式与服务器交互。
如果你使用jquery,你可以这样做:
$.ajax({
url: "test.html",
data: coords
})
.done(function() {
alert("done")
});
关于Javascript 回调和地理定位 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484181/