Accessing GeoJSON of a clicked Leaflet marker from outside the click handler function
HTML
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
<div id="map"></div>
<textarea id="outputText" rows="6" cols="60"></textarea><br>
<button class="btn" onclick="showGeoJson()">Show me the GeoJSON</button>
CSS
html,
body,
#map {
height: 500px;
width: 100%;
padding: 0px;
margin: 0px;
}
JavaScript
////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
////////////////////////////////////////////////////////////////////////////////////////////
var map = L.map('map').setView([34.069, -118.293], 14);
ATTR = '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a> | ' +
'© <a href="http://cartodb.com/attributions">CartoDB</a>';
CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
L.tileLayer(CDB_URL, {
attribution: ATTR
}).addTo(map);
/////////////////////////////////////////////////////////////////////////////////////////////
//adding data//
/////////////////////////////////////////////////////////////////////////////////////////////
var textBoxOut = document.getElementById('outputText');
var points = getPoints();
var group = L.geoJson(points).addTo(map);
alert("df");
//create global variable for text, in case button is clicked first
var textOut = 'nothing clicked';
//click handler extracts GeoJSON and assigns it to global variables
group.eachLayer(function(layer) {
layer.on('click', function() {
objectOut = layer.toGeoJSON();
textOut = JSON.stringify(objectOut);
console.log(textOut);
});
});
//Once a marker is clicked, its GeoJSON can be accessed from outside the click handler
showGeoJson = function() {
textBoxOut.value = textOut;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//GeoJSON goes here//
/////////////////////////////////////////////////////////////////////////////////////////////
function getPoints() {
var points = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-118.2931, 34.0726]
},
"properties": {}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
...