javascript 使用边界框内的数据更新 Leaflet GeoJSON 层

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15440216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:46:16  来源:igfitidea点击:

Update Leaflet GeoJSON layer with data inside bounding box

javascriptajaxleafletgeojson

提问by leosw

I'm using leaflet/JavaScript for the first time and I want to display a map, with a GeoJSON layer which change on every move… To only show points on the area.

我第一次使用传单/JavaScript,我想显示一张地图,带有一个每次移动都会改变的 GeoJSON 层......只显示该区域上的点。

This is my code source:

这是我的代码源:

// Function to refresh points to display
function actualiseGeoJSON() {
    // Default icon for my points
    var defaultIcon = L.icon({
        iconUrl: '../images/icones/cabane.png',
        iconSize: [16, 16],
        iconAnchor: [8, 8],
        popupAnchor: [0, -8]
    });

    // We create each point with its style (from GeoJSON file)
    function onEachFeature(feature, layer) {
        var popupContent = '<a href="' + feature.properties.url + '">' + feature.properties.nom + "</a>";
        layer.bindPopup(popupContent);
        var cabaneIcon = L.icon({
            iconUrl: '../images/icones/' + feature.properties.type + '.png',
            iconSize: [16, 16],
            iconAnchor: [8, 8],
            popupAnchor: [0, -8]
        });
        layer.setIcon(cabaneIcon);
    }

    // We download the GeoJSON file (by using ajax plugin)
    var GeoJSONlayer = L.geoJson.ajax('../exportations/exportations.php?format=geojson&bbox=' + map.getBounds().toBBoxString() + '',{
        onEachFeature: onEachFeature,

        pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {icon: defaultIcon});
        }
    }).addTo(map);
}

// We create the map
var map = L.map('map');
L.tileLayer('http://maps.refuges.info/hiking/{z}/{x}/{y}.png', {
    attribution: '&copy; Contributeurs d\'<a href="http://openstreetmap.org">OpenStreetMap</a>',
    maxZoom: 18
}).addTo(map);

// An empty base layer
var GeoJSONlayer = L.geoJson().addTo(map);

// Used to only show your area
function onLocationFound(e) {
    var radius = e.accuracy / 2;
    L.marker(e.latlng).addTo(map);
    actualiseGeoJSON();
}
function onLocationError(e) {
    alert(e.message);
    actualiseGeoJSON();
}
function onMove() {
    // map.removeLayer(GeoJSONlayer);
    actualiseGeoJSON();
}

map.locate({setView: true, maxZoom: 14});

// Datas are modified if
map.on('locationerror', onLocationError);
map.on('locationfound', onLocationFound);
map.on('moveend', onMove);

I have tried to remove the layer in my first function but GeoJSONlayer is not defined I have tried to remove the layer in onMove() but nothing appears I have tried to remove the layer in moveend event but I have an syntax error…

我试图在我的第一个函数中删除图层但未定义 GeoJSONlayer 我试图在 onMove() 中删除图层但没有出现我试图在 moveend 事件中删除图层但我有一个语法错误......

If somebody can help me…

如果有人可以帮助我...

Sorry for my bad English, French guy ith french function names

对不起,我的英语不好,法国人和法语函数名称

回答by flup

I see you are using the leaflet ajax plugin.

我看到您正在使用传单 ajax 插件。

The simplest way to get your map to work is to download all available data right at the start, providing a giant bounding box, and add it to the map just once. This will probably work just fine, unless there's insanely many cabins and stuff to download.

让地图工作的最简单方法是在开始时下载所有可用数据,提供一个巨大的边界框,然后将其添加到地图中一次。这可能会很好地工作,除非有大量的小屋和东西要下载。



But if you wish to refresh the data regularly, based on the bounding box, you can use the refresh method in the leaflet-ajax plugin:

但是如果你想定期刷新数据,基于边界框,你可以使用leaflet-ajax插件中的refresh方法:

you can also add an array of urls instead of just one, bear in mind that "addUrl" adds the new url(s) to the list of current ones, but if you want to replace them use refresh e.g.:

var geojsonLayer = L.geoJson.ajax("data.json");
geojsonLayer.addUrl("data2.json");//we now have 2 layers
geojsonLayer.refresh();//redownload those two layers
geojsonLayer.refresh(["new1.json","new2.json"]);//add two new layer replacing the current ones

您还可以添加一组网址而不是一个,请记住,“addUrl”会将新网址添加到当前网址列表中,但如果您想替换它们,请使用刷新,例如:

var geojsonLayer = L.geoJson.ajax("data.json");
geojsonLayer.addUrl("data2.json");//we now have 2 layers
geojsonLayer.refresh();//redownload those two layers
geojsonLayer.refresh(["new1.json","new2.json"]);//add two new layer replacing the current ones

So initially:

所以最初:

var defaultIcon = ...
function onEachFeature(feature, layer) ...

// Do this in the same scope as the actualiseGeoJSON function, 
// so it can read the variable
var GeoJSONlayer = L.geoJson.ajax(
    '../exportations/exportations.php?format=geojson&bbox=' 
    + map.getBounds().toBBoxString() + '',{
    onEachFeature: onEachFeature,

    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {icon: defaultIcon});
    }
}).addTo(map);

And then for each update:

然后对于每次更新:

function actualiseGeoJSON() {
    // GeoJSONLayer refers to the variable declared
    // when the layer initially got added
    GeoJSONlayer.refresh(
        ['../exportations/exportations.php?format=geojson&bbox=' 
        + map.getBounds().toBBoxString() + '']);
}

Alternatively, you could set the layer as a property of the map, instead of as a var:

或者,您可以将图层设置为地图的属性,而不是设置为var

map.geoJsonLayer = L.geoJson.ajax(...)

And later refer to it as follows:

以后参考如下:

map.geoJsonLayer.refresh(...)

回答by stefcud

this leaflet plugin is more suitable for your purpose, manage map events and zoom. Caching remote requests and much more.

这个传单插件更适合您的目的,管理地图事件和缩放。缓存远程请求等等。

http://labs.easyblog.it/maps/leaflet-layerjson/

http://labs.easyblog.it/maps/leaflet-layerjson/

var ajaxUrl = "search.php?lat1={minlat}&lat2={maxlat}&lon1={minlon}&lon2={maxlon}";
map.addLayer( new L.LayerJSON({url: ajaxUrl }) );

Extend L.GeoJSON with more features and support ajax or jsonp request. See the source code comments for more documentation.

使用更多功能扩展 L.GeoJSON 并支持 ajax 或 jsonp 请求。有关更多文档,请参阅源代码注释。