简体   繁体   English

当用户单击标记时,如何在使用功能组件时显示信息窗口?

[英]How do I make an infowindow appear when the user clicks the marker, while using a functional component?

The Google Maps API library I am using for this is https://github.com/JustFly1984/react-google-maps-api我使用的谷歌地图 API 库是https://github.com/JustFly1984/react-google-maps-api

What I have been asked to create is a map with multiple markers, each of which can be clicked on to open an InfoWindow centred on that marker.我被要求创建的是带有多个标记的 map,可以单击每个标记以打开以该标记为中心的信息窗口。 Much like the AirBnB search page, with the map on one side results on the other.很像 AirBnB 搜索页面,map 在另一侧结果。

However, I seem to only be able to have an InfoWindow that is open at the loading of the page and then can't be opened again.但是,我似乎只能在页面加载时打开一个 InfoWindow,然后无法再次打开。

My research so far has generally shown that I would need to completely redo this component as a class instead.到目前为止,我的研究通常表明,我需要将这个组件完全重做为 class。 Although I don't really understand the class based model of components, so ideally I wouldn't have to mess around with that.虽然我不太了解基于 class 的 model 组件,但理想情况下,我不必纠结于此。

Is there a way to make the desired effect without reworking my program entirely?有没有办法在不完全修改我的程序的情况下达到预期的效果?

This is the code for the component, in case it is relevant这是组件的代码,以防相关

import styles from '../../styles/Home.module.css';
import { Marker, LoadScriptNext, GoogleMap, InfoWindow } from '@react-google-maps/api';
import { Fragment, React } from 'react';
import { Typography } from '@material-ui/core';

export default function MapPanel(props) {
  return (
    <Fragment>
      <LoadScriptNext id='google-map-example' googleMapsApiKey="MYAPIKEY">
        <GoogleMap mapContainerStyle={{ width: "100%", height: "800px" }}
          id='google-map'
          center={props.centre}
          heading="0"
          zoom={12}>
          {addMarkers(props.markerList)}
        </GoogleMap>
      </LoadScriptNext>
    </Fragment>
  );
}

function addMarkers(markerList) {
  if (markerList != undefined) {
    return (markerList.map((marker, index) => makeMarker(marker, index)))
  }
}

function makeMarker(marker, index) {
  const handleClick = () => {
    console.log(`${marker.title} marker clicked`);
  }
  return (
    <Marker id={index} position={marker.latLong} title={marker.title} onClick={handleClick}>
      <InfoWindow id='Test' position={marker.latLong}>
        <Typography variant='body2'>{marker.text}</Typography>
      </InfoWindow>
    </Marker>
  );
}

To achieve your goal you would want to use states in your application.为了实现您的目标,您需要在应用程序中使用状态。 But since you want to deal with it using Function components, you would need to make use of react hooks to use states.但是由于您想使用 Function 组件来处理它,因此您需要使用反应钩子来使用状态。

Here is a working sample for your reference: https://stackblitz.com/edit/marker-with-infowindow-react-api-o6357y这是一个工作示例供您参考: https://stackblitz.com/edit/marker-with-infowindow-react-api-o6357y


    import ReactDOM from "react-dom";
    import React from "react";
    import {
      GoogleMap,
      Marker,
      InfoWindow,
      LoadScript
    } from "@react-google-maps/api";
    import data from "./data.json";
    
    const { useState } = React;
    const containerStyle = {
      width: "400px",
      height: "400px"
    };
    
    const center = { lat: 40.712775, lng: -74.005973 };
    
    function Map() {
      const [infoWindowID, setInfoWindowID] = useState("");
      let markers;
    
      if (data !== null) {
        markers = data.map((location, i) => {
          const marker = { lat: location.lat, lng: location.lng };
          const index = i + 1;
          return (
            <Marker
              key={index}
              position={marker}
              label={index.toString()}
              onClick={() => {
                setInfoWindowID(index);
              }}
            >
              {infoWindowID === index && (
                <InfoWindow>
                  <span>Something {index}</span>
                </InfoWindow>
              )}
            </Marker>
          );
        });
      }
      return (
        <LoadScript googleMapsApiKey="YOUR_API_KEY">
          <GoogleMap mapContainerStyle={containerStyle} center={center} zoom={10}>
            {markers}
          </GoogleMap>
        </LoadScript>
      );
    }
    
    export default React.memo(Map);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当用户单击按钮时,如何保存可重复使用的React组件? - How do i make my reusable react component saves when the user clicks button? 当我点击googlemap上的标记时,如何制作Infowindow - How can I make Infowindow when I click a marker on the googlemap 使用 google maps JS api,如何打开用户单击地图的信息窗口? 那可能吗? - Using google maps JS api, how can I open an infowindow where the user clicks on the map? Is that possible? 我希望在用户单击按钮时出现警报,但它们会提前出现 - I want alerts to appear when user clicks button, but they appear beforehand 当鼠标移出标记时,我能否使Google Maps API中的Infowindow消失,但是当鼠标从标记移至他时,我却不能消失 - Could I make Infowindow in Google maps API dissapear when mouse out of marker, but not dissapear when mouse move from marker to him infowindow 如何添加标签/标签以显示在多个对象的顶部,以便用户单击对象时标签始终面对相机? - How do I add a tag/label to appear on top of several objects so that the tag always faces the camera when the user clicks the object? 如何在标记的信息窗口中添加新按钮? - How do I add a new button to the infowindow on the marker? 如何让信息窗口停留在Google地图中标记的鼠标移出位置? - How do i let the infowindow stay on mouseout of the marker in google maps? 当用户将其单击到另一个单词时,如何创建一个可以更改单词的OnClick函数? - How do I make an OnClick function that will change a word when a user clicks it to another word? 当用户点击按钮时,如何让html运行javascript函数? - How do I make html run a javascript function when a user clicks a button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM