0

我需要在我的网站中使用地理位置作为横幅。我发现这个库似乎不错:

在我的页面中,我添加了此代码,浏览器向我显示允许获取位置的警报。

代码:

<script type="text/javascript">
    if(geo_position_js.init()){
        geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true});
    }
    else{
        alert("Functionality not available");
    }

    function success_callback(p)
    {

        var latitudine = +p.coords.latitude.toFixed(2);
        var longitudine = p.coords.longitude.toFixed(2);

        alert(latitudine+' - '+longitudine);
    }

    function error_callback(p)
    {
        alert('error='+p.message);
    }                       

</script>

我可以毫无问题地看到警报,但我需要让城市加载不同的横幅。我怎样才能做到这一点?

我还发现了这项服务:findNearbyPlaceName

它允许从纬度和经度中找到国家等,但我该如何使用这些信息?我看到他们有一个带有 xml 或 json 的回调,我试图用这段代码获取 url,但这是错误的,因为浏览器没有显示警报:

<script type="text/javascript">
    if(geo_position_js.init()){
        geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true});
    }
    else{
        alert("Functionality not available");
    }

    function success_callback(p)
    {

        var latitudine = +p.coords.latitude.toFixed(2);
        var longitudine = p.coords.longitude.toFixed(2);

        $.getJSON(
                     'http://http://api.geonames.org/findNearbyPlaceNameJSON?lat='+latitudine+'&lng='+longitudine, 
                        function(data) {
                            alert(data);
                        }
        );

    }

    function error_callback(p)
    {
        alert('error='+p.message);
    }                       

</script>
4

2 回答 2

2

您需要的是“反向地理编码器”。

使用反向地理编码器,您可以获得特定坐标的城市名称(甚至街道名称)。

一种非常简单的方法是使用 Google Maps API V2 和 V3 中提供的 Google 地理编码器:

  var geocoder;

  function codeLatLng(latitude, longitude) {
    var
        geocoder = new google.maps.Geocoder(),
        latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          // results[1].formatted_address contains the city name
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }

示例(来源):https ://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding

希望这可以帮助!

于 2012-06-02T09:17:50.050 回答
0

Geonames.org运行 web 服务,其中包括让您查找纬度/经度坐标的城市:

http://www.geonames.org/export/web-services.html#findNearbyPlaceName

支持xml和json。我可以推荐它们,不需要任何额外的 javascript 下载。

于 2012-06-03T13:14:08.617 回答