2012-02-18 5 views
0

次のコードを作成すると、都市ではなく国を取得できます。国の代わりに都市を取得するにはどうすれば変更できますか?それはそれに影響を与える可能性がある場合HTML5 - このコードでは都市の代わりに国を取得していますか?

function get_visitor_country() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position){ 
      var lat = position.coords.latitude; 
      var lon = position.coords.longitude; 
      var latlng = new google.maps.LatLng(lat, lon); 
      geocoder = new google.maps.Geocoder(); 

      geocoder.geocode({'latLng': latlng}, function(results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        if (results[1]) { 
         var country = results[results.length-1].formatted_address; 
         $("#location-detection .location-name").html(country); 
         $("#geolocation-worked").css("display", "block"); 
         $("#no-geolocation").css("display", "none"); 

         $geolocation_fix.hide().css({ height : 0 }); 

         init_geolocation_switch(); 
        } 
       } 
      }); 
     }); 
    } 
} 

スクリプトは、ファイルの末尾にhttp://maps.google.com/maps/api/js?sensor=falseをロードしています。

答えて

1

あなたのスクリプトは現在、都市や国のような特別なものは得られていません。結果から何かが得られます。

あなたが街を得、それを見つけたとき["locality", "political"]

種類セットを持つエントリの結果内の都市の検索を取得します。

var components={}; 
jQuery.each(results,function(i,v){ 
    components[jQuery.camelCase(v.types.join('-'))]=v; 
}) 

//test it 
alert((components.localityPolitical) 
     ? components.localityPolitical.formatted_address 
     : 'n/a'); 

参照:Address Component Types

便利なアクセスのためのaddressTypesで標識されたオブジェクトの


作成

関連する問題