GeocoderResult はオブジェクトの配列を返します (配列要素の数は、南極の 1 から東京の 16 までの範囲であることがわかりました)。配列内の各オブジェクトには、次のプロパティが含まれます。
- address_components: アドレスを記述する複数のオブジェクトを含む配列。これらの各オブジェクトには、long_name プロパティ (文字列)、short_name プロパティ (文字列)、および type プロパティ (配列、以下で説明) が含まれます。
- Formatted_address: アドレスを説明する直感的な単一の文字列
- ジオメトリ: 経度/緯度/視点を扱います
- タイプ: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypesで説明されています。
返された配列の最初のオブジェクトは、最も説明的な物理アドレスのように見え (これは常にそうですか?)、それに含まれる「formatted_address」は常に私のニーズを満たしているようです。問題は、1 つの文字列ではなく、各パーツが必要なことです。
たとえば、典型的な米国のformatted_addressは次のようになります:
- 米国ミシガン州ヴァン ビューレン
- State Highway 244, Roundup, MT 59072, USA
- 24 West 18th Avenue、スポケーン、WA 99203、米国
これら 3 つのformatted_addresses について、次のように取得したいと思います。
{address:null, street: null, city:"Van Buren", state:"MI", zipcode: null, country:"USA"}
{address:null, street: "State Highway 244", city:"Roundup", state:"MT", zipcode: 59072, country:"USA"}
{address:24, street: "West 18th Avenue", city:"Spokane", state:"WA ", zipcode: 99203, country:"USA"}
私は、formatted_address を解析しようとする必要がありますか? それとも、address_components を使用して、必要な部分を抽出する必要がありますか? 2 番目の解決策が最適で、次のように見えるかもしれませんが、型配列と短い/長い名前を扱うことは困難です。
getAddressParts(GeocoderResult[0].address_components) を呼び出すと、次のように動作します。
function getProp(a,type,lng) {
var j,rs;
loop:
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < a[i].types.length; j++) {
if(a[i].types[j]==type) {
rs=a[i][lng]
break loop;
}
}
}
return rs;
}
function getAddressParts(a) {
var o={};
o.street_number=getProp(a,'street_number','long_name');
o.route=getProp(a,'route','long_name'); //Street
o.establishment=getProp(a,'establishment','long_name'); //Used for parks and the like
o.locality=getProp(a,'locality','long_name'); //City
if(!o.locality){o.locality=getProp(a,'sublocality','long_name');} //Some city not available, use this one (needed for in lake michigan)?
if(!o.locality){o.locality=getProp(a,'administrative_area_level_2','long_name');} //Some city not available, use this one (needed for in lake michigan)?
o.administrative_area_level_1=getProp(a,'administrative_area_level_1','short_name'); //State
o.country=getProp(a,'country','short_name')+'A'; //A is for usA, and is just being used for testing
o.postal_code=getProp(a,'postal_code','long_name');
return o;
}