【发布时间】:2013-12-10 01:12:13
【问题描述】:
我对 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();
}
【问题讨论】:
-
您需要在您的
this.getCoordinates = function(){/*in here*/}中设置this.userPosition。请显示完整的代码。 -
它不会将值放入属性中,因为它是一个回调函数。这就是重点。
-
问题是您无法访问尚未创建的内容。
navigator.geolocation.getCurrentPosition()是异步的,这意味着它不会在成功函数内部设置值,直到它得到结果。因此,您的方法在您的属性存在之前被调用。使用 AJAX。 -
你会遇到 AJAX 的问题,就返回一个值而言,
onreadystatechange将返回到XMLHttpRequest。这使得实现你的愿望可能很困难。很多事情要考虑。 -
好的,谢谢,我可能会重新考虑我的设计。
标签: javascript callback leaflet w3c-geolocation