2017-12-22 8 views
0

を変更する属性、ここGoogleマップAPI、forループ内のマーカーと私はマップのAPIのグーグルマーカーの問題を取得しています

は、Ajaxの大成功関数のコードである(マップはその関数の引数であります)このコードを含む:

success: function(data) { 
    var tmpmap = map;       //Without this the map wont let me add markers 
    ris = JSON.parse(data);     //Parsing to json 
    for (var i = 0; i < ris.length - 1; i++) {//Here is the for 
     var id = ris[i].id_sede;    //Here i get the id from the json 
     var marker = new google.maps.Marker({ //Here i create the marker 
     map: tmpmap, 
     mid: id,       //And there is where i got that problem. 
     position: { 
     lat: parseFloat(ris[i].latitude), 
     lng: parseFloat(ris[i].longitude) 
     } 
}); 

AJAX収集したデータは、緯度、経度IDといくつかの余分な情報が含まれている通常のSQLクエリです。

したがって、forの各サイクルで、前に作成された各マーカーは、現在の "mid"(マップID)の値になります。

TL; iは周期の終わりに1 2 3及び4の中間ように、すべてのマーカーを持っていた4つのマーカーを有するDRは、中間の値の代わりに1 2 3および4

として4を有し、最終的な質問は:どのように私はこの動作を防ぐことができますか?マーカーを正しく作っていますか?そして、私がマーカーの価値を変えるとき、他のマーカーはすべて同じようにするのはなぜですか?

答えて

0

あなたは、各メーカーは、それが自分のデータです取得するように、IIFEを使用する必要があります。

success: function (data) { 
    var tmpmap = map; //Without this the map wont let me add markers 
    ris = JSON.parse(data); //Parsing to json 
    for (var i = 0; i < ris.length - 1; i++) { //Here is the for 
    // IIFE 
    (function (entry) { 
     // remember original element as variable entry 
     var marker = new google.maps.Marker({ //Here i create the marker 
     map: tmpmap, 
     mid: entry.id_sede, // still the original ID 
     position: { 
      lat: parseFloat(entry.latitude), 
      lng: parseFloat(entry.longitude) 
     } 
     }); 
    }) (ris[i]); // pass original element into IIFEE 
    } 
}); 

ため、生命維持せずに、第1のマーカーは、変数iはすでに条件ris.length - 1に達している可能性があるそのIDを取得するまで。この場合、変数idには最初のマーカーのIDは含まれません。

IIFEを使用すると、risの元のエントリ要素を使用できます。

これが役に立ちます。

+0

ありがとうございました。 –

+0

あなたは大歓迎です:) – Blauharley

+0

すべての問題の解決に役立ちましたら、それを正解とマークしてください、ありがとうございます。 – Blauharley

関連する問題