4
votes

I added external json to leaflet layer. When I click on the geojson shape/polygon, I want to get the geojson string back out. How do I do this? I have a reference to the layer, but I don't see how you can get back the geojson with properties.

var layer = e.layer;
1

1 Answers

6
votes

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/