传单 panTo(或 setview)功能?

2022-01-12 00:00:00 django leaflet jquery javascript map

我想创建一个 panTo 函数.当我单击链接时,地图会平移到坐标.但我不确定如何将值传递给函数.我开始为链接提供 Pointfield (pt) 值,如下所示:

I want to create a panTo -function. When I click a link the map pans to the coordinates. But im not sure how to pass the value to the function. I'm starting with giving the link the Pointfield (pt) value like this:

<a href="#" class="marker" value="{{ mymodel.pt }}">Link</a>

然后我一直在尝试这个:

Then I've been trying this:

$("#dialog").on("click", ".marker", function(e) {
    e.preventDefault();
    map.panTo($(this).attr("value"));
    });

那没用.我认为这是一个范围问题,函数无法读取地图"变量,因为它不在初始地图脚本下.

That didn't work. I think it's a scope-issue where the function cant read the 'map' variable because it's not under the initial map script.

所以我的下一个想法是创建一个panTo"- 函数并将其放在初始地图脚本(这将是正确的范围)下,然后从点击事件中调用该函数.不确定它会起作用,但我想知道如何从链接中传递值"?

So my next idea is to create a "panTo"- function and place it under the inital map script (which would be the right scope) and call that function from the click event instead. Not sure it would work but Im wondering how to pass it the "value" from the link?

感谢您的回答!

推荐答案

您可以利用 HTML 中的 data 属性向地图添加导航.将纬度、经度和缩放保存到类似 data-position 的位置,然后在用户单击锚标记时使用一些 JavaScript 调用这些值.这里有一些代码来说明.

You can add navigation to your map by utilizing data attributes in your HTML. Save the latitude,longitude and zoom to something like data-position and then call those values with some JavaScript when the user clicks on the anchor tag. Here's some code to illustrate.

<div id="map">
    <div id="map-navigation" class="map-navigation">
        <a href="#" data-zoom="12" data-position="37.7733,-122.4367">
            San Francisco
        </a>
    </div>
</div>

<script>
var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
                maxZoom: 18,
                attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>'
            }).addTo(map);

document.getElementById('map-navigation').onclick = function(e) {
    var pos = e.target.getAttribute('data-position');
    var zoom = e.target.getAttribute('data-zoom');
    if (pos && zoom) {
        var loc = pos.split(',');
        var z = parseInt(zoom);
        map.setView(loc, z, {animation: true});
        return false;
    }
}
</script>

相关文章