1

我正在尝试将 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)
4

3 回答 3

6

现在有一个免费的英国政府替代此处列出的其他选项。访问http://postcodes.io/以查看 API 和示例的详细信息。它还支持您所追求的反向查找

于 2014-03-20T13:48:17.673 回答
4

You could use the Google Maps reverse geocoding API. This allows you to map a lat, long pair to a set of addresses. For example:

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()
}

I put this example into a js fiddle too, here.

Hope this helps.

于 2013-05-24T00:28:29.330 回答
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/

于 2013-10-11T14:07:49.520 回答