Declaring layer
within the click handler function using var
will make it local, so you will not be able to access it outside of the click handler. If you want to access layer
globally, you will want to declare it as a global variable, either by first declaring it outside the function, or by declaring it within the function without var
. The following code uses the latter method to create two global variables, one with the layer's GeoJSON as an object and one with the GeoJSON as a string:
layer.on('click', function() {
objectOut = layer.toGeoJSON();
textOut = JSON.stringify(objectOut);
});
If you have other routines that might try to access these variables before a feature is clicked, you may want to declare them outside the click handler first (say, var textOut = 'nothing clicked'
, or the like). Here is an example fiddle using this method:
http://fiddle.jshell.net/nathansnider/pgk26r6n/