向反应图添加多个标记

时间:2020-06-16 18:32:40

标签: javascript reactjs google-maps

我正在尝试向我的Google Map添加多个标记,但是由于我是React的新手,所以我不确定如何开始。我想创建一个标记数组,并将所有标记渲染到地图上。我该怎么办?

到目前为止的代码:

import React, { Component } from 'react';
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';

const mapStyles = {
  width: '100%',
  height: '100%'
};

export class MapContainer extends Component {
  state = {
    showingInfoWindow: false,  
    activeMarker: {},          
    selectedPlace: {}          
  };

  onMarkerClick = (props, marker, e) =>
  this.setState({
    selectedPlace: props,
    activeMarker: marker,
    showingInfoWindow: true
  });

  onClose = props => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };

  render() {
    return (
      <Map
        google={this.props.google}
        zoom={14}
        style={mapStyles}
        initialCenter={{ lat: 49.166590, lng: -123.133569 }}
      >
        <Marker
          onClick={this.onMarkerClick}
          name={''}
        />

        <InfoWindow
          marker={this.state.activeMarker}
          visible={this.state.showingInfoWindow}
          onClose={this.onClose}
        >
          <div>
            <h4>{this.state.selectedPlace.name}</h4>
          </div>
        </InfoWindow>
      </Map>
    );
  }
}

我看到了

<Marker
   onClick={this.onMarkerClick}
   name={''}
/>

正在渲染标记,但是我如何使其变成循环以显示标记数组?

1 个答案:

答案 0 :(得分:0)

欢迎来到React世界。要渲染组件数组,您可以使用array.prototype.map()在整个数组中进行映射。例如

const myArray = ['hello', 'world']
  return (
    <div>
      {myArray.map((element, index) => 
        <span key = {index}>{element}</span>}
    </div>
   )
// equivalent to
// <div>
//   <span key = {0}>hello</span>}
//   <span key = {1}>world</span>}
// </div>

注意,为每个元素的根节点提供唯一的key属性非常重要。有关渲染数组的更多信息,请参见this questionthis tutorial。另外,请参见marker documentation

所以对于您的情况,举一个例子,我刚刚向渲染函数添加了一个markers数组。

render() {
let markers = [ // Just an example this should probably be in your state or props. 
  {
    name: "marker1",
    position: { lat: 49.17655, lng: -123.138564 }
  },
  {
    name: "marker2",
    position: { lat: 49.16659, lng: -123.113569 }
  },
  {
    name: "marker3",
    position: { lat: 49.15659, lng: -123.143569 }
  }
];
return (
  <Map
    google={this.props.google}
    zoom={14}
    style={mapStyles}
    initialCenter={{ lat: 49.16659, lng: -123.133569 }}
  >
    {markers.map((marker, index) => (
      <Marker
        key={index} // Need to be unique
        onClick={this.onMarkerClick}
        name={marker.name}
        position={marker.position}
      />
    ))}
    <InfoWindow
      marker={this.state.activeMarker}
      visible={this.state.showingInfoWindow}
      onClose={this.onClose}
    >
      <div>
        <h4>{this.state.selectedPlace.name}</h4>
      </div>
    </InfoWindow>
  </Map>
);
}

这是一个代码沙箱示例,其中标记处于状态。 (只需在maps.js:4中添加Google Maps API密钥即可加载地图)

Edit stoic-visvesvaraya-yc2qs