在地图上显示多个标记时,如何在点击标记时打开一个信息窗口? [英] When displaying multiple markers on a map, how to open just one info window, when clicking on a marker?

查看:217
本文介绍了在地图上显示多个标记时,如何在点击标记时打开一个信息窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 react-google-maps 来显示带有标记的地图,当你点击一个标记时,所有的信息窗口都会打开。我想在点击它时显示一个标记的信息窗口,其他人保持关闭。



这是我的代码:

 < GoogleMap 
defaultZoom = {15}
defaultCenter = {{lat:51.508530,lng:-0.076132}}
>
{props.places&& props.places.map((place,i)=>
< Marker onClick = {props.onToggleOpen} key = {i} position = {{lat:place.geometry.location.lat(),lng :place.geometry.location.lng()}}>
{props.isOpen&&< InfoWindow onCloseClick = {props.onToggleOpen}>
< div> {place.name }< / div>
< / InfoWindow>}
< /标记>
)}
< / GoogleMap>

我用这个打开和关闭InfoWindow

 从recompose导入{compose,withProps,withStateHandlers,withHandlers,withState}; $(

$ b ...

withStateHandlers(()=>({
isOpen:false,
}),{
onToggleOpen: ({isOpen,id})=>()=>({
isOpen:!isOpen,
})
}),

我正在映射所有标记,并在地图上显示它们。我怎么能点击打开一个标记InfoWindow?
这是一个相关的问题,但它不是用React制作的,不使用react-google-maps。

解决方案

这更多的是 React 问题。您可以将单击 Marker 的索引传递给 onToggleOpen ,而不是 isOpen 您使用一个 selectedPlace 状态来保存点击的 Marker 的索引,并使用此索引来渲染正确 InfoWindow



下面是一个例子(没有完全测试,但你可以得到这个想法) p>

  / *全局谷歌* / 
导入从react反应
导入{compose,withProps,withHandlers, withState,withStateHandlers}从react-google-maps
import {withScriptjs,withGoogleMap,GoogleMap,Marker,InfoWindow}
$ b $ const MyMapComponent = compose(
withProps ({
googleMapURL:https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places,
loadingElement:< div style = {{height:`100%`}} />,
containerElement:< div style = {{height:`400px`}} /> ;,
mapElement:< div style = {{height:`100%`}} />,
}),
withScriptjs,
with GoogleMap,
withState('places','updatePlaces','') ,
withState('selectedPlace','updateSelectedPlace',null),
withHandlers(()=> {
const refs = {
map:undefined,
}

return {
onMapMounted:()=> ref => {
refs.map = ref
},
fetchPlaces:({updatePlaces})=> {
让位;
const bounds = refs.map.getBounds();
const service = new google.maps.places.PlacesService(refs.map.context .__ SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
const request = {
界限:界限,
类型:['hotel']
};
service.nearbySearch(request,(results,status)=> {
if(status == google.maps.places.PlacesServiceStatus.OK){
console.log(results);
updatePlaces(results);
}
})
},
onToggleOpen:({updateSelectedPlace})=> key => {
updateSelectedPlace(key); $(b










< GoogleMap
onTilesLoaded = {props.fetchPlaces}
ref = {props.onMapMounted}
onBoundsChanged = {props.fetchPlaces}
defaultZoom = {15}
defaultCenter = {{lat:51.508530,lng:-0.076132}}
>
{props.places&& props.places.map((place,i)=>
< Marker onClick = {()=> props.onToggleOpen(i)} key = {i} position = {{lat:place.geometry.location.lat(),lng:place.geometry.location.lng() }}>
{props.selectedPlace === i&&< InfoWindow onCloseClick = {props.onToggleOpen}>
< div>
{props.places [props .selectedPlace] .name}
< / div>
< / InfoWindow>}
< ; /标记>
)}
< / GoogleMap>

$)

导出默认类MyFancyComponent extends React.PureComponent {
render(){
return(

}
}


I'm using react-google-maps to display a map with markers, and when you click on a marker, all the info windows open up. I would like to display only one marker's info window when I click on it, and for the others to stay closed.

Here is my code:

    <GoogleMap
        defaultZoom={15}
        defaultCenter={{ lat: 51.508530, lng: -0.076132 }}
    >
        {props.places && props.places.map((place, i) =>
            <Marker onClick={props.onToggleOpen} key={i} position={{ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }} >
                {props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
                  <div>{place.name}</div>
                </InfoWindow>}
            </Marker>
        )}
    </GoogleMap>

And I'm opening and closing the InfoWindow with this

import { compose, withProps, withStateHandlers, withHandlers, withState } from "recompose";

...

withStateHandlers(() => ({
  isOpen: false,
}), {
  onToggleOpen: ({ isOpen, id }) => () => ({
    isOpen: !isOpen,
  })
}),

I'm mapping over all the markers, and displaying them on the map. How could I click open just one marker InfoWindow? Here is a related question, but it's not made with React, and doesn't use the react-google-maps.

解决方案

It's more of a React question. You can pass the index of a clicked Marker to onToggleOpen and instead of isOpen you use a selectedPlace state that holds the index of a clicked Marker and use this index to render the right InfoWindow.

Here is an example (not fully tested, but you can get the idea):

/*global google*/
import React from "react"
import { compose, withProps, withHandlers, withState, withStateHandlers } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from "react-google-maps"

const MyMapComponent = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
    withState('places', 'updatePlaces', ''),
    withState('selectedPlace', 'updateSelectedPlace', null),
    withHandlers(() => {
        const refs = {
            map: undefined,
        }

        return {
            onMapMounted: () => ref => {
                refs.map = ref
            },
            fetchPlaces: ({ updatePlaces }) => {
                let places;
                const bounds = refs.map.getBounds();
                const service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
                const request = {
                    bounds: bounds,
                    type: ['hotel']
                };
                service.nearbySearch(request, (results, status) => {
                    if (status == google.maps.places.PlacesServiceStatus.OK) {
                        console.log(results);
                        updatePlaces(results);
                    }
                })
            },
            onToggleOpen: ({ updateSelectedPlace }) => key => {
                updateSelectedPlace(key);
            }
        }
    }),
)((props) => {
    console.log(props);
    return (
        <GoogleMap
            onTilesLoaded={props.fetchPlaces}
            ref={props.onMapMounted}
            onBoundsChanged={props.fetchPlaces}
            defaultZoom={15}
            defaultCenter={{ lat: 51.508530, lng: -0.076132 }}
        >
            {props.places && props.places.map((place, i) =>
                <Marker onClick={() => props.onToggleOpen(i)} key={i} position={{ lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }}>
                    {props.selectedPlace === i && <InfoWindow onCloseClick={props.onToggleOpen}>
                        <div>
                            {props.places[props.selectedPlace].name}
                        </div>
                    </InfoWindow>}
                </Marker>
            )}
        </GoogleMap>
    )
})

export default class MyFancyComponent extends React.PureComponent {
    render() {
        return (
            <MyMapComponent />
        )
    }
}

这篇关于在地图上显示多个标记时,如何在点击标记时打开一个信息窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆