2017-05-06 26 views
0

我想添加下面的do块来显示地图中的所有书籍。我使用Mapbox作为地图,但我不太清楚如何显示本书的每个图钉。我现在已经显示了一个随机位置的销钉,但很想让每个图钉都显示出来。任何指针?如何在Mapbox地图中添加do块?

<% @books.each do |book| %> 
<%= book.longitude %> 
<%= book.latitude %> 
<% end %> 

<script> 
mapboxgl.accessToken = '<%= ENV['MAP_BOX_TOKEN'] %>'; 
var geojson = { 
"type": "FeatureCollection", 
"features": [ 
    { 
     "type": "Feature", 
     "properties": { 
      "message": "Foo", 
      "iconSize": [60, 60] 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [ 
       -118.270204, 
       34.086941 
      ] 
     } 
    } 
    ] 
}; 
var map = new mapboxgl.Map({ 
container: 'map', 
style: 'mapbox://styles/mapbox/streets-v9', 
center: [-118.270204, 34.086941], 
zoom: 15 
}); 

// add markers to map 
geojson.features.forEach(function(marker) { 
// create a DOM element for the marker 
var el = document.createElement('div'); 
el.className = 'marker'; 
el.style.backgroundImage = 'url(<%= image_path "marker.svg" %>)'; 
el.style.width = marker.properties.iconSize[0] + 'px'; 
el.style.height = marker.properties.iconSize[1] + 'px'; 

// add marker to map 
new mapboxgl.Marker(el, {offset: [-marker.properties.iconSize[0]/2, -marker.properties.iconSize[1]/2]}) 
    .setLngLat(marker.geometry.coordinates) 
    .addTo(map); 
}); 
map.scrollZoom.disable(); 
map.addControl(new mapboxgl.NavigationControl()); 
</script> 

回答

0

我想通过下面的代码来做到这一点。

<script> 
mapboxgl.accessToken = '<%= ENV['MAP_BOX_TOKEN'] %>'; 

var map = new mapboxgl.Map({ 
container: 'map', 
style: 'mapbox://styles/mapbox/streets-v9', 
center: [-118.270804, 34.086241], 
zoom: 15 
}); 
<% @books.each do |book| %> 
var geojson = { 
"type": "FeatureCollection", 
"features": [ 
    { 
     "type": "Feature", 
     "properties": { 
      "message": "Foo", 
      "iconSize": [60, 60] 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [ 
       <%= book.longitude %>, <%= book.latitude %> 
      ] 
     } 
    } 
    ] 
}; 

// add markers to map 
geojson.features.forEach(function(marker) { 
// create a DOM element for the marker 
var el = document.createElement('div'); 
el.className = 'marker'; 
el.style.backgroundImage = 'url(<%= image_path "marker.svg" %>)'; 
el.style.width = marker.properties.iconSize[0] + 'px'; 
el.style.height = marker.properties.iconSize[1] + 'px'; 

// add marker to map 
new mapboxgl.Marker(el, {offset: [-marker.properties.iconSize[0]/2, -marker.properties.iconSize[1]/2]}) 
    .setLngLat(marker.geometry.coordinates) 
    .addTo(map); 
}); 

<% end %> 

map.scrollZoom.disable(); 
map.addControl(new mapboxgl.NavigationControl()); 
</script>