2017-10-24 14 views
0

私は、マーカーと情報ウィンドウをforループで出力していますが、リスト内の最後のものだけを取得しようとしています。 APIをループしてその情報を基にする必要があるため、forループがあります。しかし私の感覚では、マーカーもループに入れておくべきですか?マーカーとインフォボックスGoogleマップ

//get all the restaurants which are open 
$.getJSON(uri, function(data) { 
    for(i = 0; i < 5; i++) { 
     var place = data.response.groups[0].items[i].venue.name; 
     var placeLat = data.response.groups[0].items[i].venue.location.lat; 
     var placeLng = data.response.groups[0].items[i].venue.location.lng; 
     var placeAddress = data.response.groups[0].items[i].venue.location.formattedAddress; 
     var openPlace = data.response.groups[0].items[i].venue.hours; 
     var placeGenre = data.response.groups[0].items[i].venue.categories[0].shortName; 
     console.log(place, placeLat, placeLng, placeAddress, openPlace) 
     var placePosition = { 
      lat: placeLat, 
      lng: placeLng 
     } 

     var marker = new google.maps.Marker({ 
      position: placePosition, 
      map: map 
     }); 

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

     google.maps.event.addListener(marker, 'click', function() { 
      infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>'); 
      infowindow.open(map, this); 
     }); 
    } 
}); 
map.setCenter(pos); 
    }, function() { 
     handleLocationError(true, infoWindow, map.getCenter()); 
     }); 
    } 
    else { 
     // Browser doesn't support Geolocation 
     handleLocationError(false, infoWindow, map.getCenter()); 
    } 
    } 

私が試したし、コードを行わ見越し

+0

は、私の答えは便利ですかあなたが他の問題を抱えているんでしょうか? –

+0

私はこれを試して、他の複数のソリューションは何も動作しません。 1つの場所を設定しますが、マーカーごとに設定します。 – Chilibiff

答えて

0

いただきありがとうございます。

第1の方法: 実際には、このシナリオにはIIFEが便利です。

(function(place, placeGenre, placeAddress, openPlace, map, marker){ 
    google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>'); 
     infowindow.open(map, marker); 
    }) 
})(place, placeGenre, placeAddress, openPlace, map, marker) 

第二の方法: はあなたのループ内で関数を呼び出した後、値を渡します。

setInfowindow(place, placeGenre, placeAddress, openPlace, map, marker, infowindow); 

外setInfowindow関数を定義:

function setInfowindow(place, placeGenre, placeAddress, openPlace, map, marker, infowindow) { 
    google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent('<div><strong>' + place + ' | ' + placeGenre + '</strong><br>' + placeAddress + '<br>' + openPlace + '</div>'); 
     infowindow.open(map, marker); 
    }) 
} 
+0

こんにちは、forループを変更するソリューションが動作しませんでした! – Chilibiff

+0

これにはどんなplunker URLを入力してください。 –

+0

関数google.maps.event.addListenerは1つ以上を取ることができないようですか?私が行う場合: console.log(場所)場所はコンソールにプロットされますが、私がaddListener関数内でコンソールを実行すると、その場所は1つだけです。 – Chilibiff

関連する問題