2011-07-16 16 views
0

ジオコーダサービスからの応答結果を読み取ると、同じ場所に国コードが表示されません。シンプルなJavaScriptコードを使用してDOMから国コードを取得し、外部JSONライブラリを使用しないようにするにはどうすればよいですか?ジオコーダの応答からcountry_codeを取得する

var latlng = new google.maps.LatLng(iplat, iplong); 
    if (geocoder) { 
     geocoder.geocode({'latLng': latlng},function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (results[1]) { 
       country_code=results[1].address_components[0].short_name; 
      } 
     } 
     else 
     { 
      alert("Geocoder failed due to: " + status); 
     } 
    }); 
} 

答えて

2

address_components配列の各要素は、それ自体が、アレイであるtypes要素を含む配列です。その要素の1つとして値 "country"を含むtypes配列を持つaddress_componentsの要素を探したいとします。私が書いたことから明らかでない場合は、サンプルJSONレスポンスhttp://code.google.com/apis/maps/documentation/geocoding/を参照してください。

3
 geocoder.geocode({'latLng': latlng}, function(results, status){ 
      if (status == google.maps.GeocoderStatus.OK){ 
       if (results[1]) { 
        for (var i=0; i<results[0].address_components.length; i++) { 
        for (var b=0;b<results[0].address_components[i].types.length;b++) { 

        if (results[0].address_components[i].types[b] == "country") { 
         //this is the object you are looking for 
         country= results[0].address_components[i]; 
         break; 
        } 
        } 
        } 
        //alert(country.short_name); 
       } 
      } 
     }); 
+0

forループはさらに高速になりますが、国はいつもどこかで終わりです:) { ...} ' – Tieme

関連する問題