如何使用Javascript将Lat和Long转换为英国邮政编码

时间:2013-05-23 22:58:02

标签: javascript html5 geolocation

我正在尝试将HTML5地理位置用于我正在进行的项目。

通过地理位置获取用户所在的Lat和Long似乎相当直接。

问题是,我需要将其转换为英国邮政编码,并且因为我正在尝试学习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)

3 个答案:

答案 0 :(得分:5)

现在有一个免费的英国政府替代这里列出的其他选项。转到http://postcodes.io/以查看API和示例的详细信息。它还支持反向查找,这是你之后的

答案 1 :(得分:4)

您可以使用Google地图reverse geocoding API。这允许您将lat,long对映射到一组地址。例如:

function reverseGeoLookup(lon, lat) {
  //make a ajax request -- in prod just use whatever libraryyou have to provide this
  //probably jquery's $.get
  var req = new XMLHttpRequest()
  //put the longitude and latitude into the API query
  req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
  //this is just the result callback -- it's the function arg to $.get, essentially
  req.onreadystatechange = function() {
      if(req.readyState == 4) {
          //again jquery will parse for you, but we want the results field
          var result = JSON.parse(req.response).results
          //the maps API returns a list of increasingly general results
          //i.e. street, suburb, town, city, region, country
          for(var i = 0, length = result.length; i < length; i++) {
              //each result has an address with multiple parts (it's all in the reference)
              for(var j = 0; j < result[i].address_components.length; j++) {
                  var component = result[i].address_components[j]
                  //if the address component has postal code then write it out
                  if(~component.types.indexOf("postal_code")) {
                    var out = document.getElementById('output')
                    out.innerHTML += component.long_name
                  }
              }
          }
      }
  }
  //dispatch the XHR... just use jquery
  req.send()
}

我也把这个例子放到js小提琴中,here

希望这有帮助。

答案 2 :(得分:0)

我已经对kieran的小提琴进行了一些更改,以帮助完全回答从html5地理位置获取英国邮政编码的问题。

var x=document.getElementById("output");
getLocation();

function getLocation()
  {
  if (navigator.geolocation)
    {
       navigator.geolocation.watchPosition(reverseGeoLookup);
    }
  else
    {
       x.innerHTML="Geolocation is not supported by this browser.";
    }
  }

function reverseGeoLookup(position) {
    console.log(position);
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
  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]
                  //console.log(component.long_name);
                  if(~component.types.indexOf("postal_code")) {
                    var out = document.getElementById('output');
                    out.innerHTML = 'Approximate Post Code for your location is ' + component.long_name;
                    return false;
                  }
              }
          }
      }
  }
  req.send()
}

http://jsfiddle.net/ef72Q/28/