我真的需要帮助。 如何使用按钮单击事件打印lat和long:
<button id="geo" onclick="OnGeoClick()"> Get Location </button>
我有以下代码:
var getGeo = {
showPosition :
function showPosition(position) {
self = this;
console.log(self)
self.lat = position.coords.latitude;
self.lng = position.coords.longitude;
console.log(self);
},
showError :
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
this.err = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
this.err = "Location information is unavailable.";
break;
case error.TIMEOUT:
this.err = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
this.err = "An unknown error occurred.";
break;
}
},
getLocation :
function getLocation() {
self = this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(self.showPosition, self.showError, {enableHighAccuracy:true});
console.log(self);
} else {
self.err = "Geolocation is not supported by this browser.";}
}
};
function OnGeoClick() {...local this context binding?...}
这样窗口不存储lat和long,而是一个可以记录(结果)的可访问变量;
答案 0 :(得分:1)
您可以使用bind方法保持上下文完整。
navigator.geolocation.getCurrentPosition(self.showPosition.bind(self), self.showError, {enableHighAccuracy:true});
并像这样称呼它
function OnGeoClick() {
getGeo.getLocation();
}