Reputation: 3
I'm new to leaflets and am trying to circle the map when clicked. I want conditions like the following:
However I have the following problem:
Is there a solution to this problem?
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Polygons</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width: 900px; height: 580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [16.506174, 80.648015],
zoom: 11
}
var groupCircle = L.featureGroup();
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
map.on("click", function(e){
if(map.hasLayer(groupCircle)){
map.removeLayer(groupCircle)
}else{
new L.Circle([e.latlng.lat, e.latlng.lng], 5000).addTo(groupCircle);
map.addLayer(groupCircle)
}
})
</script>
</body>
</html>
Upvotes: 0
Views: 91
Reputation: 71
map.removeLayer(groupCircle)
groupCircle = L.featureGroup();
if(map.hasLayer(groupCircle)){
//Start
map.removeLayer(groupCircle)
groupCircle = L.featureGroup();
new L.Circle([e.latlng.lat, e.latlng.lng], 5000).addTo(groupCircle);
map.addLayer(groupCircle)
//End
}else{
new L.Circle([e.latlng.lat, e.latlng.lng], 5000).addTo(groupCircle);
map.addLayer(groupCircle)
}
map.setView([e.latlng.lat, e.latlng.lng], 11); //11 = zoom level
Here's the full code:
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Polygons</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width: 900px; height: 580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [16.506174, 80.648015],
zoom: 11
}
var groupCircle = L.featureGroup();
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
map.on("click", function(e){
map.setView([e.latlng.lat, e.latlng.lng], 11); //11 = zoom level
if(map.hasLayer(groupCircle)){
//Start
map.removeLayer(groupCircle)
groupCircle = L.featureGroup();
new L.Circle([e.latlng.lat, e.latlng.lng], 5000).addTo(groupCircle);
map.addLayer(groupCircle)
//End
}else{
new L.Circle([e.latlng.lat, e.latlng.lng], 5000).addTo(groupCircle);
map.addLayer(groupCircle)
}
})
</script>
</body>
</html>
Upvotes: 2