我最近按照本教程确定了标记所显示的点是否位于已定义的多边形内:https://www.mapbox.com/mapbox.js/example/v1.0.0/point-in-polygon/
效果很好,但它们使用ajax提取了多边形geoJSON数据并将其应用于地图。我有一个已经绘制了多边形区域的mapbox地图。我正在使用他们的API来显示我的地图。现在,我需要访问geoJSON数据以确定某个点是否在区域内。如何通过API访问该数据?
这是我提取地图,geoJSON和用于测试点是否在geoJSON区域中的函数的方式:
//mapbox connection
var mapID = "<map-id>";
L.mapbox.accessToken = "<my-token>";
//init map
var map = L.mapbox.map("mapData", mapID, {
attributionControl: false,
zoomControl: false
}).setView([53.799, -1.548], 13, {
pan: { animate: true },
zoom: { animate: true }
});
//get geoJSON
var geoJson;
$http.get("https://a.tiles.mapbox.com/v4/" + mapID + "/features.json?access_token=" + L.mapbox.accessToken).success(function(data){
geoJson = data;
});
//determine point in polygon
function determinePointInPolygon(){
var coords = [-1.3, 5.2];
var layer = leafletPip.pointInLayer(coords, L.geoJson(geoJson), true);
if (!layer.length) //point not in polygon
else //point is in polygon
}
最佳答案
集成的功能已加载到L.mapbox.featureLayer
中,该L.mapbox.Map
可作为您的map
实例的成员使用。假设您将地图实例存储在名为map.featureLayer
的引用中,则图层将为mapid
:
// Make sure the featureLayer is ready
map.featureLayer.on('ready', function (e) {
// Loop over the features
e.target.eachLayer(function (layer) {
// Do your thing
// here "layer" holds an instance of the marker/polygon/polyline
// "layer.feature" holds the actual geojson feature
});
});
这是概念的示例:http://plnkr.co/edit/D5IfRTLV0yXTqOmzNCYA?p=preview
如果愿意,也可以单独加载图块和要素,以实例化没有
addTo
的地图:var map = L.mapbox.map('mapbox', null, {
'center': [0, 0],
'zoom': 1
});
var tileLayer = L.mapbox.tileLayer('yourMapId').addTo(map);
var featureLayer = L.mapbox.featureLayer('yourMapId').addTo(map);
示例:http://plnkr.co/edit/9pYeRu6UmxuVL1TLzwPR?p=preview
然后可以省去
L.mapbox.FeatureLayer
方法,先处理要素,然后将图层添加到地图:var featureLayer = L.mapbox.featureLayer('yourMapId');
// Make sure the featureLayer is ready
featureLayer.on('ready', function (e) {
// Loop over the features
e.target.eachLayer(function (layer) {
// Do your thing
});
// Add layer to the map
e.target.addTo(map);
});
最适合您的是什么。但是我几乎忘了实际回答您的问题(尽管我认为您将不再需要此问题了),可以通过使用
getGeoJSON
的方法获得实际的GeoJSON特征集合(仅当图层已准备就绪时) :// Make sure the featureLayer is ready
featureLayer.on('ready', function (e) {
// Fetch you featurecollection
var geojson = e.target.getGeoJSON();
});