我最近按照本教程来确定标记显示的点是否位于定义的多边形内:https://www.mapbox.com/mapbox.js/example/v1.0.0/point-in-polygon/
效果很好,但他们使用 ajax 提取多边形 geoJSON 数据并将其应用到 map 上。我已经构建了一个绘制了多边形区域的 map 框 map 。我正在使用他们的 API 来显示我的 map 。我现在需要访问 geoJSON 数据以确定某个点是否在某个区域内。我如何通过 API 访问该数据?
以下是我如何提取 map 、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
的引用中,您的图层将是 map.featureLayer
:
// 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
如果您愿意,您还可以单独加载图 block 和功能,在没有 mapid
的情况下实例化您的 map :
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
然后您可以省略 addTo
方法,首先处理您的要素,然后将图层添加到 map 中:
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);
});
什么最适合你。但我差点忘了真正回答你的问题(尽管我认为你不再需要这个),实际的 GeoJSON 特征集合可以通过使用 L.mapbox.FeatureLayer
的 getGeoJSON 获得
方法(当然只有当层准备好时):
// Make sure the featureLayer is ready
featureLayer.on('ready', function (e) {
// Fetch you featurecollection
var geojson = e.target.getGeoJSON();
});
关于javascript - 从mapbox API获取geoJSON数据以确定多边形中的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078944/