我正在尝试将 HTML5 地理位置用于我正在从事的项目。
通过地理位置获取用户所在位置的纬度和经度似乎非常简单。
问题是,我需要将其转换为英国邮政编码,并且在尝试学习 javascript 时正在苦苦挣扎。
我工作的代码是:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
var Long = position.coords.longitude;
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
我找到了这个网站,它完全符合我想要实现的目标: http ://www.latlong.net/Show-Latitude-Longitude.html
谁能给我一些关于如何使它工作的提示?
任何建议都会很棒
提前致谢
========================== 修改后的代码:
//var long = '50.**************', lat = '0.**************'
var Lat='';
var Long='';
var coordsObj = {coords:{latitude:Lat, longitude:Long}};
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
console.log(position, position.coords)
console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
alert(Lat);
var Long = position.coords.longitude;
alert(Long);
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
return [Lat, Long];
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
function reverseGeoLookup(lon, lat) {
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
req.send()
}
var latlng = displayPosition(coordsObj)
reverseGeoLookup.apply(this, latlng)