0

ジオコーダーの宝石を使用している場所はほとんどありません。今私は、Google Apiを使用してGoogleマップにそれらのすべてを表示したいと思います。これまでのところ、Googleの多くの後とSO検索し、私は私のindex.html.erbにこのコードを持っている: Google apiを使ってGoogleマップにすべての位置マーカーを表示する方法

let locations = [ 
    ['<%= @location[0].address %>', '<%= @location[0].latitude %>','<%= @location[0].longitude %>'], 
    ['<%= @location[1].address %>', '<%= @location[1].latitude %>','<%= @location[1].longitude %>'], 
    ['<%= @location[2].address %>', '<%= @location[2].latitude %>','<%= @location[2].longitude %>'] 
]; 

let map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 7, 
    center: new google.maps.LatLng('<%= request.location.latitude %>', '<%= request.location.longitude %>'), 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
}); 

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

let marker, i; 

for (i = 0; i < locations.length; i++) { 
    marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(locations[i][1], locations[i][2]), 
    map: map 
    }); 

    google.maps.event.addListener(marker, 'click', (function(marker, i) { 
    return function() { 
     infowindow.setContent(locations[i][0]); 
     infowindow.open(map, marker); 
    } 
    })(marker, i)); 
} 
ここ

が、私は、データベースから動的に追加された場所が欲しいですそれを地図に表示します。私はgoogle-maps4rails gemを使用しようとしましたが、私はGoogle apiを使ってみましたので、何の結果も得られませんでした。なにか提案を?ありがとうございました:)

答えて

0

あなたの緯度と経度の値は引用符で囲まれた文字列です。これらは数字である必要があります。これらのことを引用符で囲みます。

また、ループ本体を独自の関数に入れてコードを単純化することもできます。それでは、関数を返す関数を理解することは難しくありません。これを行う簡単な方法は、ループの繰り返しごとに関数を呼び出すforEachを使用することです。

let locations = [ 
    ['<%= @location[0].address %>', <%= @location[0].latitude %>,<%= @location[0].longitude %>], 
    ['<%= @location[1].address %>', <%= @location[1].latitude %>,<%= @location[1].longitude %>], 
    ['<%= @location[2].address %>', <%= @location[2].latitude %>,<%= @location[2].longitude %>] 
]; 

let map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 7, 
    center: new google.maps.LatLng('<%= request.location.latitude %>', '<%= request.location.longitude %>'), 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
}); 

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

locations.forEach(function(location) { 
    let marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(location[1], location[2]), 
    map: map 
    }); 

    google.maps.event.addListener(marker, 'click', function() { 
    infowindow.setContent(location[0]); 
    infowindow.open(map, marker); 
    }); 
} 
+0

しかし、私は '[ '<%= @location [0] .address%>'、<%= @location [0]を印刷したい:これは理解したコードは、簡単かつ容易になりますどのように注意してください'%% @location [i] .address%>'、<%= @location [i] .latitudeのように動的に変化します。 %>、<%= @location [i] .longitude%>]、ループ内で実行されるので、次にユーザがマップに直接表示する場所を追加することができます。 – CCR

関連する問題