2

I have drawn a polygon in mapbox using leaflet and I want to change one of its property dynamically.

My code is below:

    map.js

    var map = L.map('map').setView([1.3096622448984000, 103.7689017333800], 10);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="http://mapbox.com">Mapbox</a>',
        id: 'mapbox.light'
    }).addTo(map);
    map.doubleClickZoom.disable();




    // get color depending on population density value
    function getColor(d) {
        return  d > 1000 ? '#4CA64C' :
                d > 500  ? '#6fdc6f' :
                d > 200  ? '#6fdc6f' :
                d > 100  ? '#6fdc6f' :
                d > 50   ? '#6fdc6f' :
                d > 20   ? '#6fdc6f' :
                d > 10   ? '#6fdc6f' :
                           '#FFEDA0';

    }

    function style(feature) {
        return {
            weight: 2,
            opacity: 1,
            color: '#999',
            fillOpacity: 0.7,
            fillColor: getColor(feature.properties.demand)
        };
    }

    var geojson = L.geoJson(campus, {
        style: style,
    }).addTo(map);

    function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.7
    });


    if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
        layer.bringToFront();
    }

    info.update(layer.feature.properties);

    }
function resetHighlight(e) {
    geojson.resetStyle(e.target);
     info.update();
}
function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
    map.doubleClickZoom.disable();
}


function searchText(e,feature)
{
     var layer = e.target;
     var search = {
            'zone': layer.feature.properties.name,
            'zone_id':layer.feature.id
             };
                $.ajax({
                    type: "POST",
                    contentType : 'application/json; charset=utf-8',
                    dataType : 'json',
                    url: "http://dataurl",
                    data: JSON.stringify(search), // Note it is important
                    success :function(result) {
                     // do what ever you want with data
                     //  alert("suc");

                   },
                    error:function(error){
                     //alert("success");
                      }
                });
 }


var lastClickedLayer;
function clickFeature(e) {
    if(lastClickedLayer){
         //  geojson.resetStyle(lastClickedLayer);
        }


    var layer = e.target;
        layer.setStyle({
        weight: 5,
        color: '#800000',
        dashArray: '',
        fillOpacity: 0.7,
        fillColor: getColor(1000)
        });



    lastClickedLayer = layer;
        }

function onMapClick(e,feature) {


    var layer = e.target;
    clickFeature(e);
    $("#grid_name").html(layer.feature.properties.name);

    //layer.bindPopup( '<b>'+layer.feature.properties.name+ '</b><h4><b>Demandsjfh<b></h4>'+ layer.feature.properties.demand);
    searchText(e,feature);
       setDataSet("http://data_url"+layer.feature.id);



}
function onEachFeature(feature, layer) {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        //click: zoomToFeature
        click:onMapClick

    });

}

geojson = L.geoJson(campus, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
    this._div.innerHTML = '<h4><b>Zones<b></h4>' +  (props ?
        '<b>' + props.name + '</b><br />'  
        : 'Hover over a zone');

    //props.demand=props.demand+1000;

};


info.addTo(map);

My geojson data file will look like demand.js var campus = {

        "type":"FeatureCollection","features":[
{
                        "type": "Feature",
                        "id":"04",
                        "properties": {
                            "name": "cool",
                            "demand":"1000"
                        },
                        "geometry": {
                            "type": "MultiPolygon",
                            "coordinates": [
                                [
                                    [

                                        [103.796,1.33175],[103.795,1.33092],[103.795,1.33032]               

                                    ]
                                ]
                            ]
                        }
                    }                
]};

Now I want to change the property demand by loading external JSON value from a URL.

The URL will contain JSON data for demand as

[{"demand":12}]

So I only want to change the demand property in the demand.js dynamically.

3
  • do you want to change this for permanently or for now ?Y do you want to change in demand.js ?
    – Pranav MS
    Commented Dec 9, 2016 at 10:27
  • @Pranav MS Instead of having fixed demand property I want to change it dynamically.So the demand will be in the url and if a event occurs it will fetch that particular demand.
    – joker
    Commented Dec 9, 2016 at 10:31
  • so change the json file through the jquery or JavaScript with corresponding values .
    – Pranav MS
    Commented Dec 9, 2016 at 10:33

1 Answer 1

1

You can change your json dynamically when document is ready. please gothrough the below code.

javascript

<script tyep="text/javascript">
  $(document).ready(function() {  
        var campus={"type":"FeatureCollection","features":[
                    {
                            "type": "Feature",
                            "id":"04",
                            "properties": {
                                "name": "cool",
                                "demand":"1000"
                            },
                            "geometry": {
                                "type": "MultiPolygon",
                                "coordinates": [ [ [ [103.796,1.33175],[103.795,1.33092],[103.795,1.33032]  ] ]  ]
                            }
                        }                
                ]};
                console.log(campus);  
                console.log("1 time demand in console--"+campus['features'][0]['properties']['demand']);
                campus['features'][0]['properties']['demand']=12;
                console.log("2 time demand in console after change--"+campus['features'][0]['properties']['demand']);

     });
</script>

console output enter image description here

Please try this . May this will help you. This is working in my case.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.