0

Geocoder gem을 사용하여 위치를 몇 개 추가했습니다. 이제 Google Api를 사용하여 Google지도에이 모든 것을 표시하려고합니다. 지금까지 구글의 많은 후 SO 검색, 내 index.html.erb에이 코드를 가지고 : Google api 레일을 통해 모든 위치 표시자를 표시하는 방법

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와 같이 동적으로 존재하는 단어를 .latitude %>, <% = @location [0] .longitude %>] %>, <% = @location [i] .longitude %>]를 반복하여 다음 번에 사용자가지도에 직접 표시 한 위치를 추가 할 수 있습니다. – CCR