Leaflet panTo (or setview) function?

14,597

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>
Share:
14,597
user3199840
Author by

user3199840

Python/Django Web Developer

Updated on June 04, 2022

Comments

  • user3199840
    user3199840 almost 2 years

    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.

    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?

    Thanks for your answers!

  • user3199840
    user3199840 about 10 years
    Awesome! Great answer. I'll play around with this and see if i can make it work! Thanks man
  • user3199840
    user3199840 about 10 years
    I'm trying to put the script under my "$(document).ready(function () {" where i also declare my map, tile layer and where have some other functions connected to the map. I'm wondering if i have to wrap it somehow? Or if i need to declare the dialog also? Because i've put the anchor link in a child-html which i load into a jquery dialog on the main page.