2013-01-05 96 views
1

GeocoderResult返回一個對象數組(我已經看到數組元素的數量範圍從1到南極在南極爲16)。陣列中的每個對象都包含以下屬性:從GeocoderResult獲取formatted_address組件

返回數組中的第一個對象看起來是最具描述性的物理地址(情況總是如此?),其包含的「formatted_address」似乎總能滿足我的需求。問題是我不想要一個字符串,但每個部分。

例如,一個典型的美國的formatted_address可能如下:

  • 範布倫,MI,美國
  • 國道244,農達,MT 59072,USA
  • 24西大道18號,斯波坎,WA 99203,USA

對於這三個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,並以某種方式嘗試提取我需要的部分?第二種解決方案似乎最好,看起來可能如下所示,但處理類型數組和長/短名稱使其變得困難。

如果我調用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; 
} 

回答

0

我建議使用address_components。在formatted_address中,你不知道哪個路徑表示哪個管理級別。

+0

謝謝薩爾曼,我將我的示例代碼修改爲實際上有用的東西。還有一些情況,它不完全匹配谷歌的格式化地址我嘗試使用建立,sublocality和administrative_area_level_2解決它,但也許不應該擔心它。有什麼建議麼?謝謝 – user1032531