2016-12-06 77 views
3

這裏是正在操作的谷歌地圖的plunker但在我休假回來就不再工作了。不過還是可以看看代碼更多 - https://plnkr.co/edit/jHCuVVhGDLwgjNw4bcLr谷歌地圖/ jQuery的 - 從JSON文件中創建對象

下面是谷歌地圖代碼:

var map; 

function initialize() { 
    var mapOptions = { 
     center: new google.maps.LatLng(52.4357808, 4.991315699999973), 
     zoom: 2, 
     mapTypeId: google.maps.MapTypeId.TERRAIN 
    }; 
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); 
} 

var seg = { 
    1: 'investment_cast', 
    2: 'forged_Prod', 
    3: 'air_Prod', 
    5: 'worldwide', 
    6: 'structurals' 
} 

var comp = { 
    1: 'structurals', 
    2: 'airfoils', 
    3: 'wyman', 
    4: 'energy', 
    5: 'fasteners', 
    6: 'struc_comp', 
    7: 'mech_hard', 
    8: 'engine_prod', 
    9: 'corp', 
    10: 'aero', 
    12: 'timet', 
    13: 'spec_metals' 
} 

var myJSON = {}; 
var myMarkers=[]; 

$.getJSON("locations.json", function(json1) { 
    myJSON=json1; 
    $.each(json1, function(key, data) { 
     var latLng = new google.maps.LatLng(data.latitude, data.longitude); 
     // Creating a marker and putting it on the map 
     var marker = new google.maps.Marker({ 
      position: latLng 
     }); 
     myMarkers[key]=marker; 
     marker.setMap(map); 

     var infoWindow = new google.maps.InfoWindow(); 

     google.maps.event.addListener(marker, 'click', function() { 

      if (infoWindow) {infoWindow.close();} 
      infoWindow = new google.maps.InfoWindow({ 
       content: "<h5>" + data.display_name + "</h5>" + 
       "<div>" + data.street+ "</div>" + 
       "<div>" + data.city + ", " + data.state + " &nbsp; " + data.postal_code + "</div>" + 
       "<div class='mapPhoneNum'>" + data.telephone + "</div>" + 
       "<a href=" + data.web_url + ">Website</a>" 
      }); 
      infoWindow.open(map, marker); 
      map.setZoom(15); 
      map.panTo(this.getPosition()); 

      google.maps.event.addListener(infoWindow,'closeclick',function(){ 
       resetMapOrigin(); 
      }); 

     }); 

     filterMarkers = function(category){ 

      var component = category.data("component_id"); 
      var segment = category.data("segment_id") 

      setMapOnAll(null); 
      resetMapOrigin(); 

      var filteredMarkers=[]; 

      $.each(myJSON, function(key, data) { 


       if(typeof(component)!="undefined"){ 

        if((myJSON[key].component_id == component) && (myJSON[key].segment_id == segment)){ 
        filteredMarkers.push(key); 
        } 

       }else{ 
        if(myJSON[key].segment_id == segment){ 
        filteredMarkers.push(key); 
        } 
       } 
      }); 

      for(i=0;i<filteredMarkers.length;i++){ 
       myMarkers[filteredMarkers[i]].setMap(map); 
      } 
     } 

     function setMapOnAll(map) { 
      for (var i = 0; i < myMarkers.length; i++) { 
       myMarkers[i].setMap(map); 
      } 
     } 

     function resetMapOrigin(){ 
      map.setZoom(2); 
      map.setCenter({lat:52.4357808,lng:4.991315699999973}); 
     } 
    }); 

}); 

所以問題是,var seg ={...}var comp ={...}被硬編碼到一個對象。我需要能夠做的就是使用$.getJSON(或任何其他將工作)從JSON文件扳指數據(像我與locations.json做),並設置其格式完全一樣的對象目前是1: 'structurals', 2: 'airfoils', and so on(我需要保持這種結構)。

的JSON文件格式化這樣的 -

組件:

[ 
    { 
     "id": "1", 
     "display_name": "structurals" 
    }, 
    { 
     "id": "2", 
     "display_name": "airfoils" 
    }, 
    { 
     "id": "3", 
     "display_name": "wyman" 
    }, 
    { 
     "id": "4", 
     "display_name": "energy" 
    }, 
    { 
     "id": "5", 
     "display_name": "fasteners" 
    }, 
    { 
     "id": "6", 
     "display_name": "struc_comp" 
    }, 
    { 
     "id": "7", 
     "display_name": "mech_hard" 
    }, 
    { 
     "id": "8", 
     "display_name": "engine_prod" 
    }, 
    { 
     "id": "9", 
     "display_name": "corp" 
    }, 
    { 
     "id": "10", 
     "display_name": "aero" 
    }, 
    { 
     "id": "12", 
     "display_name": "timet" 
    }, 
    { 
     "id": "13", 
     "display_name": "spec_metals" 
    } 
] 

段:

[ 
    { 
     "id": "1", 
     "display_name": "investment_cast" 
    }, 
    { 
     "id": "2", 
     "display_name": "forged_Prod" 
    }, 
    { 
     "id": "3", 
     "display_name": "air_Prod" 
    }, 
    { 
     "id": "5", 
     "display_name": "worldwide" 
    }, 
    { 
     "id": "6", 
     "display_name": "structurals" 
    } 
] 

所以,我怎麼能抓住從上面這JSON數據格式同樣的方式我目前有「seg和comp」對象嗎? (文件名是components.json和segments.json)

在此先感謝。

+0

如果您對我的答案有任何疑問,請告訴我們。謝謝 –

+0

@ agon024你甚至不關心承認任何答案。這是錯誤的。人們已經把寶貴的時間用於幫助你,你必須尊重這一點。 –

回答

1

一種解決方案是通過對象數組進行迭代,並創建與每個ID的命名屬性的另一個對象。這說明了我的意思,假設你已經獲取和分析的JSON到一個對象:

var data = 
[ 
    { 
     "id": "1", 
     "display_name": "investment_cast" 
    }, 
    { 
     "id": "2", 
     "display_name": "forged_Prod" 
    }, 
    { 
     "id": "3", 
     "display_name": "air_Prod" 
    }, 
    { 
     "id": "5", 
     "display_name": "worldwide" 
    }, 
    { 
     "id": "6", 
     "display_name": "structurals" 
    } 
]; 


var seg = {}; 
data.forEach(function(o) { 
    var x = parseInt(o.id); 
    seg[x] = o.display_name; 
}); 

console.log(seg); 
/* 
{ '1': 'investment_cast', 
    '2': 'forged_Prod', 
    '3': 'air_Prod', 
    '5': 'worldwide', 
    '6': 'structurals' } 
*/ 

其實在實踐中,我可能會使用一個實用程序庫像lodash要做到這一點,說有keyBy(): https://lodash.com/docs/4.17.2#keyBy

編輯:keyBy()不會做的正是你想要的東西,所以忽略的一部分。

編輯:另外,如果你是取3個JSON文件,這些都是異步操作,所以你需要結合可能的操作,等到所有的JSON取完成。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

0

對於你的問題:

How can I grab this JSON data from above and format it the same way that I currently have the "seg and comp" object formated?

您可以使用$.getJSON()您的其他JSON文件(即components.json和正常情況下應該在JavaScript中的承諾(或承諾庫)來完成segments.json),就像你正在用locations.json文件一樣。因爲這會導致三個異步請求,所以等待所有完成都將是有益的。 $.getJSON()返回promise,您可以等到所有承諾完成後再向地圖添加位置。

您可以使用Promise.all()在所有承諾完成後運行代碼,儘管它不支持IE。我找了一個等效jQuery的功能和閱讀this blog post是提到它後發現$.when(與.done()使用)。這種技術似乎工作:

script.js:79 Uncaught TypeError: category.data is not a function(…)

看來,這是由無線電輸入調用該函數造成的:

$.when($.getJSON("locations.json"), $.getJSON("segments.json"),  
$.getJSON("components.json")). 
    done(function(locationsResponse, segResponse, compResponse) { 
    // Each argument is an array with the following structure: [ data, statusText, jqXHR ] 
    myJSON = locationsResponse[0]; 
    var seg = segResponse[0]; 
    var comp = compResponse[0]; 
    //rest of code to add markers to the map 
    //... 
}); 

當我看着your plunker example,我也注意到在瀏覽器控制檯錯誤filterMarkers並傳遞一個字符串值,而不是對該輸入的jQuery選擇器的引用(即$(this))。因此,您可以更新輸入以全部通過該參考,並在適當的位置設置data-component_id和/或data-segment_id。例如,下面幾行:

 <div class="optGroup"><input onclick="filterMarkers($(this));" type="radio" name="loc" value="investment_cast" data-segment_id="2" data-component_id="3" /> Investment Cast Products</div> 
     <div class="optChild"><input onclick="filterMarkers(this.value);" type="radio" name="loc" value="structurals" /> PCC Structurals</div> 
     <div class="optChild"><input onclick="filterMarkers(this.value);" type="radio" name="loc" value="airfoils" /> PCC Airfoils</div> 

應更新如下:

 <div class="optGroup"><input onclick="filterMarkers($(this));" type="radio" name="loc" value="investment_cast" data-segment_id="2" data-component_id="3" /> Investment Cast Products</div> 
     <div class="optChild"><input onclick="filterMarkers($(this));" type="radio" name="loc" value="structurals" data-component_id="1" /> PCC Structurals</div> 
     <div class="optChild"><input onclick="filterMarkers($(this));" type="radio" name="loc" value="airfoils" data-component_id="2" /> PCC Airfoils</div> 

this updated plunker

0

這裏是需要plunker和重構的代碼改變Working Example變化是scripts.js文件

地名釋義我的代碼: 建立的邏輯你需要segcomp從JSON數據通過你的是循環結果並從iddisplay_name中挑選數據爲key & value

function formatData(jsonData){ 
    var obj ={}; 
    jsonData.forEach(function(item,index){ 
    var key = parseInt(item.id,10); 
    obj[key] = item.display_name; 
    }); 
    return obj; 
} 

以上功能可按需要你json數據並返回格式化的結果的對象。

接下來,因爲你希望所有的數據在你建立你的谷歌地圖之前提前出現,我會說讓我們逐個加載數據,當我們都讓我們建立地圖。

function GetAllDataSetsAndInititateMap() { 
    $.getJSON("segments.json", function(json) { 
    seg = formatData(json); 
    $.getJSON("components.json", function(json) { 
     comp = formatData(json); 
     $.getJSON("locations.json", function(json) { 
     myJSON = json; 
      BuildMap(); 
     }); 
    }); 
    }); 
} 

說完這些的地方,寫了一個名爲BuildMap新的功能,並把當前所有的代碼存在於$.getJSON("locations.json", function(json1) {塊內。

BuildMap功能看起來像

function BuildMap(){ 
    var json1 = myJSON; 
    $.each(json1, function(key, data) { 
    // all the existing code. 
    }); 
} 

這已經過測試,下面是一個Working Example in Plunker變化是scripts.js文件。

希望這有助於!