开发者问题收集

React:传递经纬度数组时出现 FitBounds 问题 - react-mapbox-gl

2017-07-13
2659

我尝试使用 fitBounds 使所有标记都以适当的缩放级别可见。

getBounds(){
   return [[12.49637,41.90278],[12.319398,45.441906],[13.055054,47.809532],[16.373724,48.208244]]
}

<Map
   style="mapbox://styles/mapbox/streets-v9"
   containerStyle={{
     height: "100%",
     width: "100%"
   }}
   fitBounds={this.getBounds()}>
     <markers /> 
</Map>

并且我收到此错误

Error: Invalid LngLat object: (12.49637,41.90278, 12.319398,45.441906)
 at new LngLat (bundle.js:118874)
 at Function.LngLat.convert (bundle.js:118874)
 at LngLatBounds.setSouthWest (bundle.js:118876)
 at new LngLatBounds (bundle.js:118876)
 at Function.LngLatBounds.convert (bundle.js:118876)
 at e.i.fitBounds (bundle.js:119021)
 at ReactMapboxGl.ReactMapboxFactory.ReactMapboxGl.componentDidMount (bundle.js:124648)
 at commons.js:19945
 at measureLifeCyclePerf (commons.js:19755)
 at commons.js:19944

我不知道这里出了什么问题。 请帮助我。

这里的 react-component 使用的是 alex3165/react-mapbox-gl

2个回答

您向 fitBounds() 函数传递了错误的边界格式。

适合边界需要以下参数: fitBounds : Array<Array<number>>

查看文档: https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md

在 mapbox 中,这被称为“LngLatBoundsLike 对象”,请参阅此处: https://www.mapbox.com/mapbox-gl-js/api/#lnglatlike

因此,您的函数调用必须是这样的:

fitBounds([[12.49637,41.90278],[12.319398,45.441906]]);

其中第一个参数是所需边界框的西南角,第二个参数是所需边界框的东北角

Andi-lo
2017-07-14

传递给 fitBounds 的输入应采用 Array<Array<number>> 的形式

getMinOrMax(markersObj, minOrMax, latOrLng) {
 if(minOrMax == "max"){
  return _.maxBy(markersObj, function (value) {
      return value[latOrLng]
  })[latOrLng];
 }else{
  return _.minBy(markersObj, function (value) {
      return value[latOrLng]
  })[latOrLng];
 }
}

getBounds(markersObj) {
  var maxLat = this.getMinOrMax(markersObj, "max", "lat");
  var minLat = this.getMinOrMax(markersObj, "min", "lat");
  var maxLng = this.getMinOrMax(markersObj, "max", "lng");
  var minLng = this.getMinOrMax(markersObj, "min", "lng");

  var southWest = [minLng, minLat];
  var northEast = [maxLng, maxLat];
  return [southWest, northEast];
}

因此,我使用上述方法从给定的标记位置对象数组中找出西南点和东北点。

标记示例对象应如下所示:

var markerPoints = [{lng:12.49637,lat:41.90278},{lng:12.319398,lat:45.441906},{lng:13.055054,lat:47.809532},{lng:16.373724,lat:48.208244}]

<Map
  style="mapbox://styles/mapbox/streets-v9"
  containerStyle={{
   height: "100%",
   width: "100%"
  }}
  fitBounds={this.getBounds(markerPoints)}>
  <markers /> 
</Map>  

注意:我在示例中使用 lodash 库来实现 min 和 max 等实用函数。

谢谢,
Josan

Jothi Sankar N Kanakavel
2017-07-16