简体   繁体   中英

react-google-maps MapWithAMarker fails to rerender when marker position changes

I took the react-google-maps MapWithAMarker example :

import React from 'react';
import { compose, withProps, lifecycle} from 'recompose';
import {
    withScriptjs,
    withGoogleMap,
    GoogleMap,
    Marker,
} from 'react-google-maps';
import keys from '../../components/config/keys';

const MapWithAMarker = compose(
    withProps({
        googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${keys.google_maps_api_key}&v=3.exp&libraries=geometry,drawing,places`,
        loadingElement: <div style={{ height: '100%' }} />,
        containerElement: <div style={{ height: '400px' }} />,
        mapElement: <div style={{ height: '100%' }} />,
    }),
    withScriptjs,
    withGoogleMap
)(props =>
    <GoogleMap
        defaultZoom={8}
        defaultCenter={{ lat: props.lat, lng: props.lng }}>
        <Marker position={{ lat: props.lat, lng: props.lng }}/>
    </GoogleMap>
);

export default MapWithAMarker;

and I use it like this:

<MapWithAMarker lat={parseFloat(excursion.lat)}
                               lng={parseFloat(excursion.lng)} />

I use React router in my application.

Observed behaviour : When i render the page for the first time, the map renders correctly. If i click on a link to rerender the page with a different marker position, the map fails to load and just renders a empty grey rectangle with only "press ctrl plus scroll to zoom" when i scroll on it.

Solved : I needed to change the defaultCenter to center and defaultZoom to zoom :

 <GoogleMap zoom={8}
            center={{ lat: props.lat, lng: props.lng }}>
     <Marker position={{ lat: props.lat, lng: props.lng }}/>
 </GoogleMap>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM