Leaflet external GeoJSON File ajax and Leaflet zoom to Features Bounds
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
<body onload="init()">
<div id="map"></div>
<div id="info">
<h2>Waiting for the Ajax Callback...</h2>
</div>
<h2>Leaflet zoom to Features Bounds</h2>
Open the popup and zoom the the feature.
<p>You can open your Chrome Developer Tools, select the frame "result(fiddle.jshell.net)" and inspect the debug variable "test".For example "test.properties.bounds_calculated"</p>
</body>
CSS
#map {
height: 400px;
}
#info {
width:250px;
height:100px;
background:rgba(255, 255, 255, 0.7);
border: 1px solid #617EF6;
border-radius:5px;
position:fixed;
top:200px;
left:calc(50% - 125px);
margin:auto;
padding:10px;
color:#617EF6;
}
JavaScript
var map, zoomFunction, test;
function init() {
map = L.map('map').setView([0, 0], 5);
// Set up the OSM layer
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
$.ajax({
type: "POST",
url: 'http://demo.boundlessgeo.com/geoserver/topp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=topp%3Astates&maxFeatures=50&outputformat=json',
dataType: 'json',
success: function (response) {
geojsonLayer = L.geoJson(response, {
onEachFeature: function (feature, layer) {
feature.properties.bounds_calculated = layer.getBounds().toBBoxString();
test = feature;
layer.bindPopup("<input type='button' value='Zoom' onclick='zoomFunction(this)' name='" + feature.properties.bounds_calculated + "'/> to the bounds of this feature<br />");
}
}).addTo(map);
map.fitBounds(geojsonLayer.getBounds());
$("#info").fadeOut(500);
}
});
}
function zoomFunction(bounds, layer) {
var array = bounds.name.split(',');
map.fitBounds(
L.latLngBounds(
L.latLng(array[1], array[0]),
L.latLng(array[3], array[2])));
}