【问题标题】:React Google Maps is not rendering markers consistentlyReact Google Maps 没有一致地呈现标记
【发布时间】:2019-02-06 23:44:51
【问题描述】:

我有以下代码在 React Google Maps 地图上呈现多个标记,但标记并不总是呈现。如果我注释掉第 1 条和第 2 条的信息,保存并取消注释该信息,标记将在 80% 的时间内呈现。如果我仅对当前位置进行硬编码,则标记将始终呈现。我不知道我在这里做错了什么,很可能是我的 ID-10-T 错误。在此先感谢您提供有关此问题的任何帮助。

/* global google */

import React from "react"
import { compose, withProps, 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?key=[api key goes here]&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `600px` }} />,
        mapElement: <div style={{ height: `75vh`, width: '50vw' }} />,
    }),
    withStateHandlers(() => ({
        isOpen: false,
    }), {
            onToggleOpen: ({ isOpen }) => () => ({
                isOpen: !isOpen,
            })
        }),
    withScriptjs,
    withGoogleMap
)((props) =>
    <GoogleMap
        zoom={15}
        center={props.currentLocation}
    >
        {props.markerList.map((marker, index) => {
            return (
                <Marker
                    position={{
                        lat: marker.lat,
                        lng: marker.lng
                    }}
                    onClick={props.onToggleOpen}
                    title={marker.name}
                    key={marker.name}
                >
                    {props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
                        <div>
                            <h3>Info Window</h3>
                            <h4>Testing</h4>
                        </div>
                    </InfoWindow>}
                </Marker>
            )
        })};

    </GoogleMap>
);

const markers = [
    {
        lat: 38.3332416,
        lng: -95.63961839999999,
        name: "bar 1"
    },
    {
        lat: 38.0332416,
        lng: -95.63971639999999,
        name: "bar 2"
    }
];

class MyFancyComponent extends React.PureComponent {
    state = {
        isMarkerShown: false,
    }


    componentWillMount() {
        this.getGeoLocation()
    }

    getGeoLocation = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                position => {
                    this.setState({
                        currentLatLng: {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude,
                            name: "current location"
                        }
                    })
                    markers.unshift(this.state.currentLatLng);
                }
            )
        } else {
            error => console.log(error)
        }
    }

    render() {
        return (
            <MyMapComponent
                currentLocation={this.state.currentLatLng}
                markerList={markers}
            />
        )
    }
}

export default MyFancyComponent;

【问题讨论】:

    标签: google-maps react-google-maps


    【解决方案1】:

    关键是位置确定时(执行Geolocation.getCurrentPosition() 的回调函数)MyMapComponent 组件可能已经被渲染,这很可能是标记渲染不一致的原因。

    为了消除这种行为,可以考虑以下解决方案。

    由于MyFancyComponent 已经是一个有状态的组件,我建议引入markers 状态并像这样设置初始值:

    class MyFancyComponent extends React.PureComponent {
      state = {
        isMarkerShown: false,
        markers: markers
      };
    
      //...
    }
    

    然后,一旦确定了当前位置,状态就可以像这样更新:

    getGeoLocation = () => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(position => {
    
            let latLng = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
                name: "current location"
              };
    
            this.setState( prevState => ({
              currentLatLng: latLng,
              markers: [latLng,...prevState.markers]
            }));
          });
        } else {
          error => console.log(error);
        }
      };
    

    最后作为 props 传入MyMapComponent 组件:

    <MyMapComponent
            currentLocation={this.state.currentLatLng}
            markerList={this.state.markers}
          /> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 2018-02-03
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多