javascript - 如何使用 react-google-maps 通过点击在 map 上添加标记?

标签 javascript reactjs google-maps google-maps-api-3 react-google-maps

我正在努力寻找一个非常简单的示例,说明当用户在基于组件的 React-google-maps 中左键单击 map 时如何向 Google map 添加标记。需要帮助。

const Map = withScriptjs(withGoogleMap((props) =>
  <GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
    onClick = {props.onMapClick}
   >
  {props.isMarkerShown && <Marker position={props.markerPosition} />}

 </GoogleMap>
))

export default class MapContainer extends React.Component {
  constructor (props) {
    super(props)
    this.state = {

   }
 }

render () {
  return (
  <div style={{height: '100%'}}>
    <Map
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places"
      loadingElement={<div style={{ height: `100%` }} />}
      containerElement={<div style={{ height: `400px` }} />}
      mapElement={<div style={{ height: `100%` }} />}
      placeMarker={this.placeMarker}
    />
  </div>
)
 }
 }

最佳答案

这是一个通用示例,演示了如何在 map 点击时显示标记:

const Map = compose(
    withStateHandlers(() => ({
        isMarkerShown: false,
        markerPosition: null
      }), {
        onMapClick: ({ isMarkerShown }) => (e) => ({
            markerPosition: e.latLng,
            isMarkerShown:true
        })
      }),
    withScriptjs,
    withGoogleMap
)
    (props =>
        <GoogleMap
            defaultZoom={8}
            defaultCenter={{ lat: -34.397, lng: 150.644 }}
            onClick={props.onMapClick}
        >
            {props.isMarkerShown && <Marker position={props.markerPosition} />}

        </GoogleMap>
    )

export default class MapContainer extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <div style={{ height: '100%' }}>
                <Map
                    googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places"
                    loadingElement={<div style={{ height: `100%` }} />}
                    containerElement={<div style={{ height: `400px` }} />}
                    mapElement={<div style={{ height: `100%` }} />}
                />
            </div>
        )
    }
}

Live demo

关于javascript - 如何使用 react-google-maps 通过点击在 map 上添加标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274808/

相关文章:

javascript - 谷歌地图只加载了它的一半,我使用了一些额外的 javascript 来对 map 产生一些影响,但它只加载了一半

javascript - Bootstrap SelectPicker 在初始化时复制选择列表

javascript - 当浏览器位置改变时重新渲染 React.js

javascript - 在链接上 react onClick 事件

javascript - 正确的 React 方式来处理父组件中仅作用于选定子组件的函数?

iPhone 开发 - 在 map 上显示两个位置

javascript - 通过 JQuery Load 加载 Google Map?

javascript - 比较 ECMA6 集合是否相等

javascript - 想要隐藏密码输入

javascript - 当用户滚动到平滑滚动的部分时,如何添加事件类?