问题
I have some code that detects when the market is dragged inside and outside of a circle.
This works great but I was just wondering how I can have one market and multiple circles detected instead of just one.
Here is the current code:
var mymap = L.map('mapid', {
center: [50.895763, -1.150556],
zoom: 16
});
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoic3RldmVuc2F0Y2giLCJhIjoiY2p5eDR6MWgzMHRvbjNocnJkN2d2MjRwaSJ9.wd0OtBUQQfUtNxdduQA3lg', {
maxZoom: 18,
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
var marker = new L.marker([50.896422, -1.148444],{
draggable: true,
autoPan: true
}).addTo(mymap);
var circle = L.circle([50.895763, -1.150556], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 100
}).addTo(mymap);
marker.on('drag', function(e) {
var d = mymap.distance(e.latlng, circle.getLatLng());
var isInside = d < circle.getRadius();
circle.setStyle({
fillColor: isInside ? 'green' : '#f03'
})
});
But I would like to add multiple circles instead of just one.
How can I do this?
回答1:
Put the circles in an array and forEach()
over them with the radius test - something like this (substitute your own method of setting up the circles)
var mymap = L.map("mapid", {
center: [50.895763, -1.150556],
zoom: 16
});
L.tileLayer(
"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1Ijoic3RldmVuc2F0Y2giLCJhIjoiY2p5eDR6MWgzMHRvbjNocnJkN2d2MjRwaSJ9.wd0OtBUQQfUtNxdduQA3lg",
{
maxZoom: 18,
attribution:
'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: "mapbox.streets"
}
).addTo(mymap);
var marker = new L.marker([50.896422, -1.148444], {
draggable: true,
autoPan: true
}).addTo(mymap);
var circles = [];
circles[0] = L.circle([50.895763, -1.150556], {
color: "red",
fillColor: "#f03",
fillOpacity: 0.5,
radius: 100
}).addTo(mymap);
circles[1] = L.circle([some - other - coordinates], {
color: "red",
fillColor: "#f03",
fillOpacity: 0.5,
radius: 100
}).addTo(mymap);
marker.on("drag", function(e) {
circles.forEach(function(circle) {
var d = mymap.distance(e.latlng, circle.getLatLng());
var isInside = d < circle.getRadius();
circle.setStyle({
fillColor: isInside ? "green" : "#f03"
});
});
});
来源:https://stackoverflow.com/questions/57400995/leaflet-geofence-on-multiple-circles-detecting-marker-inside-outside