ycr ycr - 2 months ago 13
HTML Question

JSFiddle Function not working

My JSFiddle function is not working, The function

getAllLocations
when the button is clicked does not get executed. Your help is appreaciated.

The HTML

<div id="map" style="width: 800px; height:500px" align="center"></div>
<br>
<button type="button" onclick="getAllLocations();">GET ALL THE LOCATIONS</button>

<div>
<h3>Output Console</h3>

<textarea id="TextArea" rows="8" cols="80"></textarea>
<br>
</div>


JS

var map = L.map('map').setView([ 10.88869, 10.85878 ], 18);

L.tileLayer(
'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png',
{
maxZoom : 20,
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://mapbox.com">Mapbox</a>',
id : 'examples.map-i86knfo3'
}).addTo(map);

var poly = L.polyline([], {
color : 'green'
});
poly.addTo(map);

map.on('click', function(e) {
poly.addLatLng(e.latlng);

//alert();
});

function getAllLocations(){
alert ("Test");
var locArray = poly.getLatLngs();
var area = document.getElementById('TextArea');

for(var i=0; i<locArray.length; i++){

var item2 = locArray[i];
var item3 = "" + item2;
var item4 = item3.split("(");
var item5 = item4[1].split(")")
//alert(item5[0]);

area.value += item5[0] + "\n";


}
}


JS Fiddle

Answer

It seems your context is being changed function is going out of scope. Define your function like this and it will work so that the function is global.

getAllLocations = function (){
alert ("Test");
    var locArray = poly.getLatLngs();
    var area = document.getElementById('TextArea');

    for(var i=0; i<locArray.length; i++){

        var item2 = locArray[i];
        var item3 = "" + item2;
        var item4 = item3.split("(");
        var item5 = item4[1].split(")")
        //alert(item5[0]);

        area.value += item5[0] + "\n";


    }
}