使用Mapbox GL JS绘制半径为英里/米的圆

jrr*_*dnx 26 mapbox-gl-js

我正在将地图从使用mapbox.js转换为mapbox-gl.js,并且无法绘制使用英里或米的半径而不是像素的圆圈.该特定圆圈用于显示从中心点到任何方向的距离区域.

以前我可以使用以下内容,然后将其添加到图层组:

// 500 miles = 804672 meters
L.circle(L.latLng(41.0804, -85.1392), 804672, {
    stroke: false,
    fill: true,
    fillOpacity: 0.6,
    fillColor: "#5b94c6",
    className: "circle_500"
});
Run Code Online (Sandbox Code Playgroud)

我在Mapbox GL中发现的唯一文档如下:

map.addSource("source_circle_500", {
    "type": "geojson",
    "data": {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [-85.1392, 41.0804]
            }
        }]
    }
});

map.addLayer({
    "id": "circle500",
    "type": "circle",
    "source": "source_circle_500",
    "layout": {
        "visibility": "none"
    },
    "paint": {
        "circle-radius": 804672,
        "circle-color": "#5b94c6",
        "circle-opacity": 0.6
    }
});
Run Code Online (Sandbox Code Playgroud)

但是这会以像素为单位呈现圆形,但不会缩放.目前是否有一种方法可以让Mapbox GL渲染一个带有圆(或多个)的图层,该图层基于距离和缩放比例?

我目前正在使用Mapbox GL的v0.19.0.

Bra*_*yer 65

我已经使用GeoJSON多边形为我的用例解决了这个问题.它不是严格的圆形,但通过增加多边形的边数可以非常接近.

这种方法的另一个好处是它可以自动地用地图正确地改变它的音高,大小,方位等.

这是生成GeoJSON多边形的函数

var createGeoJSONCircle = function(center, radiusInKm, points) {
    if(!points) points = 64;

    var coords = {
        latitude: center[1],
        longitude: center[0]
    };

    var km = radiusInKm;

    var ret = [];
    var distanceX = km/(111.320*Math.cos(coords.latitude*Math.PI/180));
    var distanceY = km/110.574;

    var theta, x, y;
    for(var i=0; i<points; i++) {
        theta = (i/points)*(2*Math.PI);
        x = distanceX*Math.cos(theta);
        y = distanceY*Math.sin(theta);

        ret.push([coords.longitude+x, coords.latitude+y]);
    }
    ret.push(ret[0]);

    return {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": [{
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [ret]
                }
            }]
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

map.addSource("polygon", createGeoJSONCircle([-93.6248586, 41.58527859], 0.5));

map.addLayer({
    "id": "polygon",
    "type": "fill",
    "source": "polygon",
    "layout": {},
    "paint": {
        "fill-color": "blue",
        "fill-opacity": 0.6
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您需要更新稍后创建的圆圈,可以这样做(请注意需要获取data属性以传递给setData):

map.getSource('polygon').setData(createGeoJSONCircle([-93.6248586, 41.58527859], 1).data);
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样:

示例图像

  • 更清洁的解决方案是使用草皮圈:https://github.com/Turfjs/turf/tree/master/packages/turf-circle (3认同)
  • 先生,你是个天才。做得好! (2认同)
  • @BradDwyer当前样式不允许设置笔触宽度。默认值为1。您只能设置笔触颜色。我将多边形的填充颜色设置为透明,这似乎可行。需要跨浏览器进行测试。 (2认同)

fph*_*ipe 30

在阐述Lucas的答案时,我想出了一种估算参数的方法,以便根据特定的度量大小绘制一个圆.

地图支持0到20之间的缩放级别.假设我们按如下方式定义半径:

"circle-radius": {
  stops: [
    [0, 0],
    [20, RADIUS]
  ],
  base: 2
}
Run Code Online (Sandbox Code Playgroud)

由于我们定义了最小缩放级别(0)和最大缩放级别(20)的值,因此地图将在所有缩放级别渲染圆圈.对于它之间的所有缩放级别,它导致半径(大约)RADIUS/2^(20-zoom).因此,如果我们设置RADIUS与我们的度量值匹配的正确像素大小,我们将获得所有缩放级别的正确半径.

所以我们基本上是在一个转换因子之后将米转换为缩放级别20的像素大小.当然这个因素取决于纬度.如果我们在最大缩放级别20处测量赤道水平线的长度并除以该线跨越的像素数,我们得到一个因子~0.075m/px(每像素米).应用墨卡托纬度比例因子1 / cos(phi),我们获得任何纬度的正确米到像素比:

const metersToPixelsAtMaxZoom = (meters, latitude) =>
  meters / 0.075 / Math.cos(latitude * Math.PI / 180)
Run Code Online (Sandbox Code Playgroud)

因此,设置RADIUSmetersToPixelsAtMaxZoom(radiusInMeters, latitude)让我们得到一个正确大小的圆:

"circle-radius": {
  stops: [
    [0, 0],
    [20, metersToPixelsAtMaxZoom(radiusInMeters, latitude)]
  ],
  base: 2
}
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,停止语法现在可以替换为插值表达式: `"circle-radius": ["interpolate",["exponential", 2],["zoom"],0, 0, 20,200]` (4认同)
  • 仅供参考,您可以将公式中的 0.075 值替换为“78271.484 / 2 ** Zoom”。例如:`78271.484 / 2 ** 20 = 0.07464550399780273`。该值来自:https://docs.mapbox.com/help/glossary/zoom-level/ (3认同)
  • @Jan,它是求幂运算符:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation (2认同)

dhr*_*v10 11

扩展@fphilipe的答案并跟进评论:-

Mapbox 使用正确表达式执行此操作的方法是

'circle-radius': [
  'interpolate',
  ['exponential', 2],
  ['zoom'],
  0, 0,
  20, [
    '/',
    ['/', meters, 0.075],
    ['cos', ['*', ['get', 'lat'], ['/', Math.PI, 180]]],
  ],
],
Run Code Online (Sandbox Code Playgroud)

这假设您的要素属性包含纬度作为名为“lat”的标签。您只需更换meters变量即可。

另外:为了提高精度,建议在停止点中包含缩放级别,我尝试了以下代码,但由于某种原因它不起作用。没有抛出任何错误,但圆半径不准确。

'circle-radius': [
  'interpolate',
  ['exponential', 2],
  ['zoom'],
  0, 0,
  20, [
    '/',
    ['/', meters, ['/', 78271.484, ['^', 2, ['zoom']]]],
    ['cos', ['*', ['get', 'lat'], ['/', Math.PI, 180]]],
  ],
]
Run Code Online (Sandbox Code Playgroud)

如果有人弄清楚了这一点,请发表评论(无需使用视口信息和状态管理动态传递缩放级别)。很抱歉没有将此作为后续评论发布。谢谢!

  • 你的第一个简单的解决方案对我来说似乎非常精确。我添加了一个用 Turf 创建的圆形图层,并且在所有缩放(至少从 14 到 19)下都完美匹配。很棒的解决方案。 (2认同)

Rah*_*hul 8

虽然所有的答案都很复杂,但这里是最简单的答案

文档

var center = [84.82512804700335, 26.241818082937552];
var radius = 5;
var options = {steps: 50, units: 'kilometers', properties: {foo: 'bar'}};
var circle = turf.circle(center, radius, options);
Run Code Online (Sandbox Code Playgroud)

演示链接

结果

在此处输入图片说明


Luc*_*ski 5

此功能未内置于 GL JS 中,但您可以使用函数来模拟它。

<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8' />
  <title></title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.19.0/mapbox-gl.js'></script>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.19.0/mapbox-gl.css' rel='stylesheet' />
  <style>
    body {
      margin: 0;
      padding: 0;
    }
    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>
</head>

<body>

  <div id='map'></div>
  <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoibHVjYXN3b2oiLCJhIjoiNWtUX3JhdyJ9.WtCTtw6n20XV2DwwJHkGqQ';
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v8',
      center: [-74.50, 40],
      zoom: 9,
      minZoom: 5,
      maxZoom: 15
    });

    map.on('load', function() {
      map.addSource("source_circle_500", {
        "type": "geojson",
        "data": {
          "type": "FeatureCollection",
          "features": [{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [-74.50, 40]
            }
          }]
        }
      });

      map.addLayer({
        "id": "circle500",
        "type": "circle",
        "source": "source_circle_500",
        "paint": {
          "circle-radius": {
            stops: [
              [5, 1],
              [15, 1024]
            ],
            base: 2
          },
          "circle-color": "red",
          "circle-opacity": 0.6
        }
      });
    });
  </script>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

重要注意事项:

  • 确定特定实际测量的函数参数并不简单。它们随着要素的经度/纬度而变化。
  • 由于平铺数据的性质以及我们为 WebGL 打包数据的方式,大于 1024px 的圆圈将无法正确渲染


ham*_*ami 5

使用@turf/turf 的简单方法

import * as turf from "@turf/turf";
import mapboxgl from "mapbox-gl";

map.on('load', function(){
let _center = turf.point([longitude, latitude]);
let _radius = 25;
let _options = {
  steps: 80,
  units: 'kilometers' // or "mile"
};

let _circle = turf.circle(_center, _radius, _options);

map.addSource("circleData", {
      type: "geojson",
      data: _circle,
    });

map.addLayer({
      id: "circle-fill",
      type: "fill",
      source: "circleData",
      paint: {
        "fill-color": "yellow",
        "fill-opacity": 0.2,
      },
    });


});
Run Code Online (Sandbox Code Playgroud)

重要的提示

在这种情况下使用mapboxgl v1如果你使用mapboxgl v2你得到一个错误

**Uncaught ReferenceError: _createClass is not defined**
Run Code Online (Sandbox Code Playgroud)

要解决此错误,您必须使用以下方法 https://github.com/mapbox/mapbox-gl-js-docs/blob/6d91ce00e7e1b2495872dac969e497366befb7d7/docs/pages/api/index.md#transpiling-v2