2012-06-02 21 views
0

我需要在我的网站中使用地理位置来定位横幅。 我发现this library这看起来不错:使用geo.js进行地理定位

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

代码:

<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> 

回答

2

你需要的是一个“反向地理编码” 。

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

一个非常简单的方法是使用谷歌的地理编码器在谷歌地图API V2和V3可供选择:

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

希望这有助于!

+0

谢谢,但是我怎样才能使用Maps API获取Lat和long? –

+0

就包括谷歌地图API <脚本类型= “文/ JavaScript的” SRC = “http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE”> (你一个来自https://code.google.com/apis/console的API Key) 现在你可以调用你的codeLatLng方法了success_callback function:function success_callback(p){var latitudine = + p.coords.latitude.toFixed 2); var longitudinaline = p.coords.longitude.toFixed(2); codeLatLng(纬向,纵向); } – libjup

+0

它帮助你,基督徒?不要忘记标记答案已被接受。 – libjup