Mapbox:创建一个具有边框半径(图层)的矩形

问题描述 投票:0回答:2

我一直在尝试获得与您在此处看到的相同的图层。但我找不到合适的类型和选项。目前我只使用了一个圆圈,但我无法为 X 轴和 Y 轴提供不同的填充。

这是预期的层(对于非聚集点)

这是我的代码:

    map.addLayer({
    id: 'unclustered-point',
    type: 'circle',
    source: 'places',
    filter: ['!', ['has', 'point_count']],
    paint: {
        'circle-color': '#486fd1',
        'circle-radius': 20,
    }
});

map.addLayer({
    id: 'unclustered-point-count',
    type: 'symbol',
    source: 'places',
    filter: ['!', ['has', 'point_count']],
    layout: {
        'text-field': ['get', 'price'],
        'text-font': ['DIN Offc Pro Bold'],
        'text-size': 11,
    },
    paint: {
        'text-color': "#fff",
    }
});

这就是我现在所拥有的:

javascript mapbox mapbox-gl
2个回答
0
投票

详情

我有一个类似的案例,我没有找到使用mapbox SDK的方法,所以我决定挖掘其他方法,这就是我解决它的方法:

  • 使用画布创建圆角矩形
  • 将其设为位图
  • 将其作为符号图层添加到mapbox地图中
  • 在其上添加文本图层

此外,由于设备像素比的原因,它在 MacBook 和 iPhone 上看起来会像素化,所以我们需要考虑这一点

这是我的解决方案


const dpr = window.devicePixelRatio;

const getRoundedRectangleImage = async ({color, width, height, radius}) => {
  // Make the image not pixelized on devices with high DPR
  const canvas = document.createElement('canvas');
  canvas.width = width * dpr;
  canvas.height = height * dpr;
  const ctx = canvas.getContext('2d')!;

  ctx.scale(dpr, dpr);

  // Draw rounded rectangle
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.roundRect(0, 0, width, height, [radius]);
  ctx.fill();

  const image = await createImageBitmap(canvas);
  return image;
}

// ...

// Add image to map
getRoundedRectangleImage({
  width: 68, 
  height: 36,
  color: '#486fd1',
  radius: 100,
}).then((image) => {
  map.addImage('rounded-rectangle', image);
});

// Add layer to display rounded rectangles
map.addLayer({
  id: 'rounded-rectangle-layer',
  type: 'symbol',
  source: 'YOUR_SOURCE',
  filter: ['!', ['has', 'point_count']],
  layout: {
    'icon-image': 'rounded-rectangle',
    'icon-size': 1 / dpr, // compensate device pixel ratio
    'icon-allow-overlap': true,
    'text-allow-overlap': true,
  },
});

// Display over rounded rectangles text
map.addLayer({
  id: 'count-text',
  type: 'symbol',
  source: 'YOUR_SOURCE',
  filter: ['!', ['has', 'point_count']],
  layout: {
    'text-field': ['get', 'price'],
    'text-font': ['DIN Offc Pro Medium'],
    'text-size': 11,
    'text-justify': 'center',
   },
   paint: {
     'text-color': '#fff',
   },
});


-1
投票

不确定,但我认为这可行。

'circle-radius': {
        'base': 1,
        'stops': [[0, 10], [20, 30]] 
    },
© www.soinside.com 2019 - 2024. All rights reserved.