2014-11-24 38 views
0

我試圖從JQ獲取Lat和Long值的國家和城市名稱。解析Google地圖JSON數據以在JQ(非JQuery)中進行地理編碼

下面是完整的例子JSON https://maps.googleapis.com/maps/api/geocode/json?latlng=55.397563,10.39870099999996&sensor=false

我粘貼在jqplay返回的JSON,

試圖選擇國家和城市的名字,但我得到的最接近的是

.results[0].address_components[].short_name 

哪有我指定只需將節點"types" : [ "country", "political" ]

謝謝

回答

0

這是我不清楚正是你要尋找的。每個結果都有一組類型,每個地址組件也有一組類型。你想要哪一個?我們可以編寫一個與您嘗試的內容相匹配的過濾器,但考慮到這些數據,這對您來說將毫無用處。包含您列出的類型的唯一項目只是一個國家/地區名稱。

無論如何,假設您想要得到類型爲"country""political"的結果對象,請使用過濾器。

.results | map(
    select(
     .types | contains(["country","political"]) 
    ) 
) 

否則,你需要澄清你從這個數據集究竟想要什麼。預期結果的一個例子...

0

我寫了一個函數來做到這一點。

/** 
* geocodeResponse is an object full of address data. 
* This function will "fish" for the right value 
* 
* example: type = 'postal_code' => 
* geocodeResponse.address_components[5].types[1] = 'postal_code' 
* geocodeResponse.address_components[5].long_name = '1000' 
* 
* type = 'route' => 
* geocodeResponse.address_components[1].types[1] = 'route' 
* geocodeResponse.address_components[1].long_name = 'Wetstraat' 
*/ 
function addresComponent(type, geocodeResponse, shortName) { 
    for(var i=0; i < geocodeResponse.address_components.length; i++) { 
    for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) { 
     if (geocodeResponse.address_components[i].types[j] == type) { 
     if (shortName) { 
      return geocodeResponse.address_components[i].short_name; 
     } 
     else { 
      return geocodeResponse.address_components[i].long_name; 
     } 
     } 
    } 
    } 
    return ''; 
} 

使用方法;一個例子:

... 
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK && results[1]) { 
    var country  = addresComponent('country', results[1], true); 
    var postal_code = addresComponent('postal_code', results[1], true); 
    ... 
    } 
}); 
... 

我曾經在這裏:saving marker data into db

0

的JSON分配給結果變量VAR的結果= {您的JSON}。 那就試試這個:

for(var idx in results.results) 
{ 
    var address = results.results[idx].address_components; 
    for(var elmIdx in address) 
    { 
     if(address[elmIdx].types.indexOf("country") > -1 && 
      address[elmIdx].types.indexOf("political") > -1) 
     { 
      address[elmIdx].short_name //this is the country name 
      address[elmIdx].long_name //this is the country name 

     } 
    } 
}  
相關問題