[英]Tom select maxOptions with stimulus.js controller [Rails]
[英]Making a rails 7 stimulus controller handle values dynamically
虽然可以安装leaflet
并生成 map,
./bin/importmap pin leaflet
手动添加leaflet.css
文件到assets/stylesheets
和 images 到public/images
目录,
刺激 controller 设置为 static 值。
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "placeholder" ]
connect(){
import("leaflet").then( L => {
this.map = L.map(this.placeholderTarget,{zoomDelta:0.5,zoomSnap:0.5}).setView([ 47.1960, 9.023 ], 10);
var base_map = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.map);
var marker1 = L.marker([47.4, 8.9]).addTo(this.map);
var marker2 = L.marker([47.0, 9.3]).addTo(this.map);
});
}
disconnect(){
this.map.remove()
}
}
坐标将位于页面的其他位置。
假设文档将具有 ' id
'、'lon_1'、'lat_2'、'lon_2'、'zoom'、'lat_marker_1'、'lon_marker_1'、'lat_marker_2'、'lon_marker_2' 的 ID,那么应该如何转换这个 controller
这是一个 XY 问题。 它说对于几乎所有编程语言/框架,如果您使用以_n
结尾的标识符(变量名称、id、属性等),那么您做错了,应该使用列表/数组/映射/散列/对象代替。
如果你想通过 DOM 传递一堆 Map 标记,只需使用一个元素,如列表和数据属性:
<ul id="cities">
<li data-lat="40.781944" data-lon="-73.966111">New York</li>
<li data-lat="19.076111" data-lon="72.87751">Mumbai</li>
<li data-lat="50.45" data-lon="30.523333">Kyiv</li>
</ul>
如果您在页面上以表格的形式显示相同的数据,这很有意义。 否则,您可能需要考虑设置一条路由,将数据提供为 JSON。
如果您愿意,也可以像vue-leaflet 那样使用自定义元素。
如果您随后想将这些标记添加到 map,您只需循环遍历元素:
let cities = document.getElementById('cities');
for (const city of cities.children) {
let marker = L.marker([city.dataSet.lat, city.dataSet.lon]);
marker.addTo(this.map);
}
请记住,您不必为 DOM 中的所有内容分配 id,并且像那样构建 JS 并不是一个好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.