TransWikia.com

Add marker to coordinates Leaflet

Geographic Information Systems Asked by Wayne05 on June 17, 2021

i work with RStudio and Leaflet. I like to add inputboxes to type coordinates into them. Then the code should set a marker on this point and zoom on it.

How can i do this?
I tried to manipulate the html code with: but it does not run 🙁 . I think there is a missing specification on my current map.

Please help 🙂

    <div id="map"></div>
    <div>
      <label for="x">X: </label>
      <input type="text" id="x">
      <label for="y">Y: </label>
      <input type="text" id="y">
      <button type="button" onclick="goThere()">Go</button>
    </div>
var secondProjection = "+proj=lcc +lat_1=29.7 +lat_0=29.7 +lon_0=-5.4 +k_0=0.9996155960000001 +x_0=500000 +y_0=300000 +a=6378249.2 +b=6356515 +towgs84=31,146,47,0,0,0,0 +units=m +no_defs";
  var firstProjection ="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "
<script>
  function goThere() {
    var x = document.getElementById('x').value;
    var y = document.getElementById('y').value;
    
    var pj = proj4(secondProjection,firstProjection,[x, y]);
    var lng = pj[0];
    var lat = pj[1];
    var latlng = L.latLng(lat, lng);
    L.marker(latlng).addTo(map);
    map.setView(latlng, 10);
  }
</script>

One Answer

Hmm I don't use proj4 so I can't help you for it, but just with this code :

function goThere() {
    var x = document.getElementById('x').value;
    var y = document.getElementById('y').value;

    var latlng = L.latLng(y, x);
    L.marker(latlng).addTo(map);
    map.setView(latlng, 10);

}

You are good to go !

So add it to your HTML in a script tag like this :

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

        var OpenStreetMap_Mapnik =L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        });
        
        OpenStreetMap_Mapnik.addTo(map);
        
        function goThere() {
            var x = document.getElementById('x').value;
            var y = document.getElementById('y').value;
        
            var latlng = L.latLng(y, x);
            L.marker(latlng).addTo(map);
            map.setView(latlng, 10);
          }
          </script>

And your inputboxes should work : enter image description here

Hope it can help !

Answered by Quentin N on June 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP