React中的谷歌地图折线

时间:2016-12-01 03:02:35

标签: google-maps reactjs

  • 如何在React Component中绘制谷歌地图Polylines
  • 是否有可用的库来执行此操作?

2 个答案:

答案 0 :(得分:0)

结帐react-google-maps我目前正尝试用google-map-react来解决这个问题,但我认为由于折线不能直接支持,所以它有点棘手。

如果您只是想获取地图,那么google-map-react可能足以满足您的需求,但react-google地图有一个内置折线组件,如下所示:

<Polyline
   onClick={_.noop}
   onRightClick={_.noop}
   onDragStart={_.noop}
/>

哪个非常好。 (:

答案 1 :(得分:0)

以下代码适用于我(取自使用React和Meteor的真实项目)

我的项目中使用的库:

[关于以下内容的简介:将显示一个地图,其上有几个标记,有连接标记的折线(红色),来自1-> 2-&gt; 3-&gt; ; ...-&GT;端。标记列表代表我的餐厅列表,标记将包含弹出窗口,其中包含餐厅的标题,将通过单击

打开
  constructor(props){
    super(props);

    this.state = {
      bounds: [],
      marker_list: [],
      spots: [],
    }

    // my restaurant list contains JSON data for restaurant, containing something like ...
    // {title: 'restaurant name', location: {coordinates: ['Lng','Lat']}, /* ... */ }
    myRestaurantList.forEach(section => {
      this.state.bounds.push([section.location.coordinates[1],section.location.coordinates[0]])
      this.state.spots.push(
          {
            title: section.title,
            // ...
          }
      )
    })
  }

  componentDidMount(){
    L.Icon.Default.imagePath = '/packages/bevanhunt_leaflet/images';
    var map = L.map('mapID').setView(this.state.bounds[0], 13);
    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
          attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
          maxZoom: 18,
          id: 'mapbox.streets',
          accessToken: 'YOUR-TOKEN-HERE'
      }).addTo(map);
    var that = this;
    this.state.bounds.map(function(coor, index) {
      var options = {
        clickable: true,
        icon: L.AwesomeMarkers.icon({icon: '', prefix: 'glyphicon',markerColor: 'green',html: '<span class="badge badge-notify" style="background-color: white; padding: 1px 0px 0px; width: 16px; height: 16px; border-radius: 8px; font-size: 11px; color: black">'+(index+1)+'</span>',}),
      };
      var popup = L.popup({className: 'popupClass', autoPan: true})
        .setLatLng(coor)
        .setContent('<div style="width:250px;height:auto;">'+that.state.spots[index].title+'</div>');
      that.state.marker_list[index] = L.marker(coor,options).bindPopup(popup);
      that.state.marker_list[index].addTo(map);
    });
    var polyline = L.polyline(this.state.bounds, {color: 'red'}).addTo(map);
    map.fitBounds(this.state.bounds);       
  }

  render() {
    return (
        <div id="mapID" style={{width: '100%', height: '400px'}}></div>
    )
  }