Sunday 21 July 2019

Dynamically set mapview based on the overlay feature of L.geoJson coordinates in Leaflet


I want to dynamically setView of the map based on the overlay feature which I extract from L.geoJson in Leaflet. I tried using fitBounds, which doesn't seem to work. Here is the code snippet:


 var counties = $.ajax({
url:"http://localhost:8080/geoserver/........../&maxFeatures=50&outputFormat=application/json",

dataType: "json",
success: console.log("data successfully loaded."),
error: function (xhr) {
alert(xhr.statusText)
}
})

$.when(counties).done(function(){
var map = L.map('map')
.setView([52.30, 8.23], 15); //I want to set the coordinates dynamically here like setActiveArea

// .setActiveArea('activeArea', true, true);

// Map layer

var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}).addTo(map);

//Style layer for counties
var geojsonMarkerOptions = {

radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};

// Add requested external GeoJSON to map
var ky = L.geoJSON(counties.responseJSON, {

style: geojsonMarkerOptions
}).bindPopup(function (layer) {
return ("Name of the field:"+(layer.feature.properties.name)+'
'+"Name" +(layer.feature.properties.sid)+"sid");
}).addTo(map);

//Just a try, doesnt seem to work either
ky.on('load', function() {
map.fitBounds(ky.getBounds(), {maxZoom: 3});
});
});


I tried using Leaflet plugin https://github.com/Mappy/Leaflet-active-area but got a blank output. Is there any other way to dynamically use the overlay coordinates and set it as a map view?



Answer



The answer is in your code. Just try modifying the last piece of code with getbounds(). It seems that your getting a null value, hence ur getting a blank output.


Try making these changes.



  1. Comment setView function in ur code



  $.when(counties).done(function(){

var map = L.map('map');
// .setView([52.30, 8.23], 15);


  1. Remove the ky.on() code and add setView function to map with required directions. Before this check what value ur getting in getbounds in developer options, this should help you debug better.



 console.log(counties.getbounds());
map.setView(counties.getBounds()['_southWest''], 15)


Make sure to give either one of the bound as shown above (NE or SW), this could resolve your issue.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...