2

I want to in Leaflet write a coordinatepair (lat/long) in a form and then click a button to zoom to the coordinatepair.

I'm really new on this.

2 Answers 2

7

To zoom to a point in Leaflet, you can use PanTo: (Leaflet Doc #PanTo)

map.panTo(new L.LatLng(47, 15));

Create a text input field for Latitude and Longitude in HTML, and a button as well.

Latitude: <input type="text" name="lat" id="lat"/>
Longitude: <input type="text" name="lng" id="lng"/>
<input type="button" onclick="zoomTo()" value="zoomTo"/>

Read the values with Javascript and put it in PanTo method:

function zoomTo() {
    var lat = document.getElementById("lat").value;
    var lng = document.getElementById("lng").value;
    map.panTo(new L.LatLng(lat, lng));
}   

Here's a code chunk, runable and tested:

<html>
<head>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <style>
        #mapid { height: 500px; }
    </style>
</head>
<body>
    Latitude: <input type="text" name="lat" id="lat"/>
    <br/>
    Longitude: <input type="text" name="lng" id="lng"/>
    <input type="button" onclick="zoomTo()" value="zoomTo"/>
    <div id="mapid"></div>

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

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    function zoomTo() {
        var lat = document.getElementById("lat").value;
        var lng = document.getElementById("lng").value;
        map.panTo(new L.LatLng(lat, lng));
    }   
</script>
</body>
</html>
3

Just as a quick example:

HTML

<input id="myForm" type="text" value="Type here">
<button onclick="zoom2latLng();">Zoom to Coords</button>

javascript

// get input
var inputLatLng = document.getElementById('myForm').value;
// declare leaflet latlng
var latlng = L.latLng(inputLatLng);  // ie. 50.5, 30.5
// declare leaflet map
var map = L.map('map' .... ;

function zoom2latLng() {
    map.flyTo(latlng);  // you can specify pan/zoom options as well
};

This is just an example; not runnable code. Pulled from the leaflet documentation

Not the answer you're looking for? Browse other questions tagged or ask your own question.