首页 > 解决方案 > 使用 ReactJS 更新标记而不更新 Google 地图中心

问题描述

我正在使用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),
                            }}
                    />
                ))
            }
        </>
    );
}

谢谢您的帮助。

标签: javascriptreactjsgoogle-mapsgoogle-maps-markers

解决方案


这是我的错,只需替换center它就defaultCenter可以了。


推荐阅读