微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我想在 ReactJS 应用程序中单击谷歌地图标记时显示信息窗口?

如何解决我想在 ReactJS 应用程序中单击谷歌地图标记时显示信息窗口?

我使用了 infoWindow,但是当我点击标记时,没有显示 infoWindow。单击标记将如何显示?我正在从道具中获取标记。地图上显示标记,但这些标记不可点击。如果我在 Click 上调用一个函数显示警报框,则所有数据都显示在警报框中。但我只想在点击标记时打开 infoWindow。

import React,{ Component } from "react";
import { Map,GoogleApiWrapper,Marker,InfoWindow } from 'google-maps-react';
import logo from '../assests/fbicon.png'

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

class LiveLocation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lati: "",long: "",isOpen: false,showingInfoWindow: false,activeMarker: {},selectedplace: {},markerMap: "",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
      });
    }
  }
  handletoggleOpen = () => {

    this.setState({
      isOpen: true
    });
  }

  handletoggleClose = () => {
    this.setState({
      isOpen: false
    });
  }

  displayMarkers = () => {
    console.log(this.props.store)
    return this.props.store.map((stores,index) => {
      console.log(stores._id)
      return (
        <Marker
          key={index}
          position={{ lat: stores.lat,lng: stores.lng }}
          label={index}
          onClick={() => this.handletoggleopen()}
          icon={{url:logo,scaledSize:new window.google.maps.Size(40,40)}}
        >

          {
            this.state.isOpen && 
            <InfoWindow  onCloseClick={this.onClose}>
              <span>Something</span>
            </InfoWindow>
          }

        </Marker>
      );
    });
  };

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => {
      this.setState({
        lati: position.coords.latitude,long: position.coords.longitude
      });
    });
  }


  render() {
    return (
      <>
        {console.log(this.props)}
        <div>
          <Map
            google={this.props.google}
            zoom={10}
            style={mapStyles}
            initialCenter={{
              lat: this.props.lati,lng: this.props.long

            }}
          >
            {this.displayMarkers()}
          </Map>

        </div>

      </>
    );
  }
}

解决方法

我在您提供的代码中注意到了一些事情,

  1. 您将 initialCenter 设置为 this.props.lati and this.props.long,但是我注意到您正在 componentDidMount 中获取用户的位置,您在其中设置了 latilong 的状态。您的道具中是否有 lati 和 long 变量,或者您的意思是使用状态中的 lati 和 long 变量?如果是这样,您需要使用 this.state.lati or this.state.long。您的状态值为空,它会将初始中心默认为 (0,0)。如果您希望它以用户位置为中心,请使用 center 参数而不是 initialCenter

  2. 在 Marker 对象中的 onClick 中,您需要调用 {this.onMarkerClick} 函数,并且可以删除 handleToggleOpenhandleToggleClose 函数。您还可以在您所在的州删除这些:

   isOpen: false,markerMap: "",selectedPlace: ""
  1. 在标记中的标签参数中,您传递的是 {index} 并且它的数据类型不是字符串。标签需要字符串才能工作。你可以让它{index.toString()}。

  2. 要显示信息窗口,您无需将其附加到 displayMarkers 函数中的对象内。将它放在您在 Map 对象中调用 {this.displayMarkers()} 之后。

您可以查看我为实现您的用例而制作的此 code 和代码片段。请注意,我使用了示例 props 值,并且只使用了地图中心的 props 值。其余的,我从你的代码中得出。要使代码正常工作,您需要放置 API 密钥。

代码片段

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

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

class LiveLocation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lati: this.props.center.lat,long: this.props.center.lng,showingInfoWindow: false,activeMarker: {},selectedPlace: {}
    };
  }

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

  onInfoWindowClose = () => {
    this.setState({
      activeMarker: null,showingInfoWindow: false
    });
  };
  



  displayMarkers = () => {
    return this.props.store.map((stores,index) => {
      return (
        <Marker
          key={index}
          position={{ lat: stores.lat,lng: stores.lng }}
          label={index.toString()}
          name={stores.id}
          onClick={this.onMarkerClick}
          //icon={{url:logo,scaledSize:new window.google.maps.Size(40,40)}}
        />
      );
    });
  };

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(position => {
      this.setState({
        lati: position.coords.latitude,long: position.coords.longitude
      });
    });
  }

  render() {
    return (
      <>
        <div>
          <Map
            google={this.props.google}
            zoom={14}
            style={mapStyles}
            initialCenter={{
              lat: this.state.lati,lng: this.state.long
            }}
          >
            {this.displayMarkers()}
            <InfoWindow
              marker={this.state.activeMarker}
              onClose={this.onInfoWindowClose}
              visible={this.state.showingInfoWindow}
            >
              <div>
                <h4>{this.state.selectedPlace.name}</h4>
              </div>
            </InfoWindow>
          </Map>
        </div>
      </>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'YOUR_KEY'
})(LiveLocation);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?