javascript map in leaflet how to refresh

2019-03-18 16:13发布

问题:

i have a basic geoJson program in javascript by using leaflet API.

<html>
<head>

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<script src="india.js" type="text/javascript"></script>

</head>


<body>
<div id = "map1" style="width: 1100px; height: 400px"> </div>

<script>

var area = L.map('map1', {center: [27.8800,78.0800], zoom: 4 });

L.tileLayer('http://a.tiles.mapbox.com/v3/raj333.map-gugr5h08/{z}/{x}/{y}.png').addTo(area);

var indiaLayer= L.geoJson(india, {style: {weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.1}});

        area.addLayer(indiaLayer);

        function clicked(){

        this.options.style.fillOpacity = 0.8;
            //how to refresh layer in the given map

        }

        indiaLayer.on('click', clicked);                
</script>
</body>
</html>

the problem is how would i automatically refresh the content of Layer on the map.

example here

             function clicked(){

        indiaLayer.style.fillOpacity = 0.8;
            //how to refresh layer in the given map

        }

        indiaLayer.on('click', clicked);   

when user click on indiaLayer , the fillOpacity variable changes but doesn't reflect back on map which is understood since i am not refreshing the map. I don't know how to do it.

please help

P/s: these are the functions available on indiaLayer object (i.e. this object inside clicked function...which one to use for this purpose or there exist none)

You can check the list of methods available of GEOJson in the Leaflef documentation This is the link to v.0.7.7, which is the closest available to used in this example.

回答1:

Last time I've used

map._onResize(); 

and that help me refresh map. Maybe a little hack, but, it work.

In your code will be area._onResize()

P.S: Maybe you should try change the way to set new opacity value - try change

function clicked(){
    this.options.style.fillOpacity = 0.8;
 }

to that

function clicked(){
    this.setStyle({fillOpacity: 0.2});
 }


回答2:

map.invalidateSize();

map._onResize() - it's a hack, and there is no guarantee that it won't be removed in future versions.



回答3:

area.fitBounds(area.getBounds());