Ad

How To Use Foreach In Jstl + Javascript?

- 1 answer

I try add pin in Google map. I have collection ${list} items with coordinate and name. Everyone item I want put in map. I write some code:

<script>
function initMap() {
<c:forEach items="${list}" var="item">
    var cairo = {lat: ${item.geometry.lat}, lng: ${item.geometry.lng}};
    var map = new google.maps.Map(document.getElementById('map'), {
        scaleControl: true,
        center: cairo,
        zoom: 10
    });
    var infowindow = new google.maps.InfoWindow;
    infowindow.setContent('${item.name}');
</c:forEach>
}

But my code don't work correct. This add in map only one (last) item from collection.

Please help.

Ad

Answer

you may need create a Marker point to map

function initMap() {

var cairo =new google.maps.LatLng(38.54,77.02); 

var map = new google.maps.Map(document.getElementById('map'), {
    scaleControl: true,
    center: cairo,
    zoom: 10
});

<c:forEach items="${list}" var="item">

var infowindow = new google.maps.InfoWindow;

infowindow.setContent('${item.name}');

var myLatlng = new google.maps.LatLng(${item.geometry.lat}, ${item.geometry.lng});

 var marker = new google.maps.Marker({
    position : myLatlng,
    map : map,
    icon : 'img/icon.png' 
    title:${item.name}
   }); 
   google.maps.event.addListener(marker, 'click', function() {  
    // map.setZoom(15);  
    // map.setCenter(marker.getPosition());  
     infowindow.open(map, marker);  
    });  
  </c:forEach>

 }
Ad
source: stackoverflow.com
Ad