首页 > 解决方案 > 传单:即使在移动或缩放之后,画圆也始终可见并居中

问题描述

我试图在我的传单地图上画一个圆圈,即使用户移动或放大地图,它也应该始终可见并居中。以下代码在用户移动地图时效果很好,但是当用户放大或缩小时,圆圈的大小不会更新。我想始终保持圆的相同尺寸。

HTML

<div id="map" class="map" style="height:75vh;"></div>

JS

// Init Leaflet Map basically
this.map = L.map("map").setView([38.63, -90.23], 12);
window.map = this.map;
this.tileLayer = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
   maxZoom: 20,
   maxNativeZoom: 18,
   attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
});

this.tileLayer.addTo(this.map);

// Create circle that will be always visible and will have alwaus the same width.
this.circle = L.circle([38.63, -90.23], 3000, {
  color: '#5d78ff',
  fillOpacity: 0
}).addTo(this.map);

// Set circle always centered when map is moved.
this.map.on("moveend", (s) => {
  this.circle.setLatLng(this.map.getCenter());
});

// todo: Set circle always centered when map is zoom in/out
this.map.on("zoomend", (s) => {
  this.circle.setLatLng(this.map.getCenter());
  console.log('test');
});

JSFIDDLE

https://jsfiddle.net/4uorasdn/

标签: javascriptleaflet

解决方案


您可以使用CircleMarker而不是使用 Circle。

需要更改的代码的相关部分应如下所示。

this.circle = L.circleMarker([38.63, -90.23], {
  radius: 200,
  color: '#5d78ff',
  fillColor: '#f03',
  fillOpacity: 0.2,
  opacity: 1,
  title: "test"   
}).addTo(this.map);

你可以在这里找到一个工作的 jsfiddle


推荐阅读