如何在直线上显示距离标记(Mapbox-gl)?

时间:2018-12-14 01:31:11

标签: mapbox mapbox-gl turfjs

我想在用addlayer:线绘制的路线上显示公里标记。使用@ turf / along,我可以计算距离标记的坐标,但是在地图上显示它们的一种好方法是什么?也欢迎使用非草皮相关的方法。

我想在路线线本身上或某个米跨之间的线下方显示坐标,例如每100m。

2 个答案:

答案 0 :(得分:1)

您可以为距离标签创建symbol类型的新层。

由于您已经能够计算其坐标,因此剩下要做的就是使用这些坐标创建源并将其连接到具有以下字段的布局:

  • text-field和距离字符串(例如'text-field': '{distance}km',如果您在源属性中设置了距离)
  • text-offset,具有相对于其中心的相对偏移。注意:单位是ems,而不是米。

示例(未经测试):

{
  id: 'distance-label',
  type: 'symbol',
  source: 'distance-labels',
  paint: {
    'text-color': '#00f'
  },
  layout: {
    'symbol-placement': 'point',
    'text-font': ['Open Sans Regular','Arial Unicode MS Regular'],
    'text-field': '{distance}km',
    'text-offset': [0, -0.6],
    'text-anchor': 'center',
    'text-justify': 'center',
    'text-size': 12,
  }
}

答案 1 :(得分:0)

出于我的目的,我想在路线线上显示每整公里的距离标签(这就是routeDistance铺地板的原因)。

//distanceLabel object
var distanceLabels = {
  "type": "FeatureCollection",
  "features": []
}

//added it as a map source
map.addSource('distanceLabels', {
  "type": "geojson",
  "data": distanceLabels
})

//added distancLabels as a map layer
map.addLayer({
  "id": "distanceLabels",
  "type": "symbol",
  "source": "distanceLabels",
  "paint": {
    'text-color': '#000000'
  },
  "layout": {
    'symbol-placement': 'point',
    'text-font': ['Open Sans Regular','Arial Unicode MS Regular'],
    'text-field': '{distance}\n{unit}',
    'text-anchor': 'center',
    'text-justify': 'center',
    'text-size': 13,
    'icon-allow-overlap': true,
    'icon-ignore-placement': true
  }
})


//render labels function
 renderDistanceMarkers() {
  var unit = this.isMetric == true ? 'kilometers' : 'miles'
  var unitShort = this.isMetric == true ? 'km' : 'mi'

  //calculate line distance to determine the placement of the labels
  var routeDistance = turf.length(route.features[0], {units: unit})

  //rounding down kilometers (11.76km -> 11km)
  routeDistance = Math.floor(routeDistance)
  var points = []

  //only draw labels if route is longer than 1km
  if(routeDistance !== 0) {
    // Draw an arc between the `origin` & `destination` of the two points

    for (var i = 0; i < routeDistance + 1; i++) {
      var segment = turf.along(route.features[0], i, {units: unit})

      if(i !== 0) { //Skip the initial point (start coordinate)
          points.push({
              "type": "Feature",
              "properties": {'unit': unitShort},
              "geometry": {
                  "type": "Point",
                  "coordinates": segment.geometry.coordinates
              }
          })
      }

    }

    distanceLabels.features = points

    //update distances for the label texts
    for(var i = 0; i < points.length; i++) {
      distanceLabels.features[i].properties.distance = i + 1 //First one would be 0
    }

    //render now labels
    map.getSource('distanceLabels').setData(distanceLabels)

  }
},