【问题标题】:Update markers without updating Google Maps center with ReactJS使用 ReactJS 更新标记而不更新 Google 地图中心
【发布时间】:2021-03-06 16:28:22
【问题描述】:

我正在使用react-google-maps v9.4.5 库。当我更新标记时,地图的中心也会更新。如何在不影响地图的情况下更新标记?

我已经尝试过使用 redux 并更新状态。

我尝试了这里的示例:https://codesandbox.io/s/qzj7qp4p2w?file=/src/Map.js

但它无法识别我在 Markers.js 中使用的变量 google

GoogleMaps.js

import React from "react";
import {
    withGoogleMap,
    GoogleMap,
    Marker,
    withScriptjs
} from "react-google-maps";

import Markers from "./Markers";

class GoogleMaps extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <GoogleMap
                zoom={this.props.zoom}
                center={this.props.center}>
                //My own component
                <Markers markers={this.props.markers}/>
            </GoogleMap>
        );
    }
}

export default withScriptjs(withGoogleMap(GoogleMaps));

Markers.js

import React from "react";
import {
    Marker,
} from "react-google-maps";

export default function Markers(props) {
    const google = window.google;
    return (
        <>
            {
                props.markers.map((marker, index) => (
                    <Marker
                        key={index} position={{lat: marker.lat, lng: marker.lng}}
                        icon={{
                                url: marker.icon,
                                size: new google.maps.Size(32, 32),
                            }}
                    />
                ))
            }
        </>
    );
}

感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs google-maps google-maps-markers


    【解决方案1】:

    这是我的错,只需将 center 替换为 defaultCenter 即可。

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 1970-01-01
      • 2020-05-30
      • 2012-08-25
      • 1970-01-01
      • 2019-08-16
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多