问题
I'm not sure why my for-loop for adding circles to a leaflet layer isn't working.
Here's my code:
var linkDistance = $('#linkDistance').val();
var nodesCount = 8;
var bandwidth = "10 GB/s";
// gps coords for 505 Marquette
var rootLongitude = 35.088878;
var rootLatitude = -106.65262;
var mymap = L.map('mapid').setView([rootLongitude, rootLatitude], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
function drawNext() {
var coords = [];
for (var i = 0; i <= nodesCount; i++) {
var radius = linkDistance*1000;
var angle = Math.PI*2*i/nodesCount;
var dx = radius*Math.cos(angle);
var dy = radius*Math.sin(angle);
coords.push([(rootLatitude + (180/Math.PI)*(dy/EARTH_RADIUS)), (rootLongitude + (180/Math.PI)*(dx/EARTH_RADIUS)/Math.cos(rootLatitude*Math.PI/180))]);
}
for (var i = 0; i < coords.length; i++) {
new L.Circle(coords[i], 200, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(mymap);
console.log("added circle to: " + coords[i]);
}
}
drawNext()
;
The map loads but no circles are appearing. I have no trouble making a single circle, but it seems like the for loop makes it break. What's the proper way to do this using leaflet? Thanks!
回答1:
- You have syntax issues, in particular at
L.Circle(coords[i], 500), {... - You forgot to add your circles to the map.
- Not really a technical problem, but note that the first coordinate in Leaflet is called "latitude" and the second "longitude", not the reverse. Latitude cannot be outside [-90; 90] range by definition.
- Depending on the value of your
linkDistance, the chosen initial zoom level may not display your circles in the view port.
Demo: https://jsfiddle.net/3v7hd2vx/59/
来源:https://stackoverflow.com/questions/38755435/how-does-one-make-circles-using-a-for-loop-with-leaflet