Leaflet – Entering Manual Coordinates to Draw Polygon

leafletleaflet-draw

I want the user to enter manual coordinates of a polygon and then to click on a button to draw the polygon.

My code:

<body>
    <div>
        Polygon: <input type="text" name="coordPolygon" id="coordPolygon"/><br>
        <input type="button" onclick="drawPolygon()" value="Draw"/><br>
    </div>
    <script>
        function drawPolygon() {
            var latlngs = document.getElementById("coordPolygon").value;
            polygon = L.polygon(latlngs, {color:'red'});
            polygon.addTo(mymap);
        }
    </script>
</body>

When the user enters for example [[48,-3],[50,5],[44,11],[43,-2]] the console tells me:

TypeError: latlngs is null

Note: I didn't test Leaflet.draw, I want to try with it later

Best Answer

I saw this resembled the leaflet example and that worked but this failed because the value from a textbox is seen as a string, you need to convert it to an object and you can do this with JSON.parse.

Try This...

<!DOCTYPE html>
<html>
<head>

<title></title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>

<style>
html, body, #map {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
</style>
</head>
 <body>   
 <div>
        Polygon: <input type="text" name="coordPolygon" id="coordPolygon"/><br>
        <input type="button" onclick="drawPolygon()" value="Draw"/><br> 
    </div>
</br>
<div id="map"></div>

    <script>
            var map = L.map('map').setView([48,-3], 7); 

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

                osm.addTo(map);

        function drawPolygon() {
            //var coords =  [[48,-3],[50,5],[44,11],[48,-3]] ;          
            var coords = document.getElementById("coordPolygon").value;

            var a = JSON.parse(coords);

            var polygon = L.polygon(a, {color: 'red'});
            polygon.addTo(map);

            map.fitBounds(polygon.getBounds());
        }
    </script>
</body>
</script>
</head>
</html>