当来自 props 的数据集发生更改时,带有标记的 react-google-maps 折线不会更新地图

问题描述

我正在使用 react-google-maps 库来在地图上显示 polylinesmarkers,为此我使用了这个示例以及来自 props 的数据集(非硬编码)它工作正常。

现在我想要实现的是在来自 props 的数据集发生变化时更新地图,我已经记录并检查了数据及其在每个动作中的变化,但地图不会自行更新。

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

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=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={7} defaultCenter={{ lat: -34.897,lng: 151.144 }}>    /* All these coordinates are coming from props */
    <polyline 
      options={{
        strokeColor: "red",strokeOpacity: 0.75,strokeWeight: 2,icons: [
            {
                // icon: linesymbol,offset: "0",repeat: "20px"
            }
        ]}} 
      path={[{ lat: -34.397,lng: 150.644 },{ lat: -35.397,lng: 151.644 }]}   /* All these coordinates are coming from props */
    />
    <polyline 
      options={{
        strokeColor: "blue",icons: [
            {
                // https://developers.google.com/maps/documentation/javascript/examples/overlay-symbol-custom
                icon: {
                  path: "M -2,0 0,-2 2,2 z",strokeColor: "blue",fillColor: "blue",fillOpacity: 1,},lng: 155.644 },lng: 151.644 }]}
    />

    <Marker position={{ lat: -35.397,lng: 151.644 }} onClick={props.onMarkerClick} />  /* All these coordinates are coming from props */
    <Marker 
      position={{ lat: -34.397,lng: 155.644 }} onClick={props.onMarkerClick}   /* All these coordinates are coming from props */
      icon={{
        url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',}}
    />
    <Marker 
      position={{ lat: -34.397,lng: 150.644 }}     /* All these coordinates are coming from props */
      onClick={props.onMarkerClick}
      title="click on it!!"
      label="A"
    />
  </GoogleMap>
));

function Map() {

  const handleMarkerClick = () => {
    alert('Marker Clicked');
  }

  return (
    <MyMapComponent onMarkerClick={handleMarkerClick} />
  )
}

export default Map;

请有人指导我如何使用来自道具的更改数据定期更新地图。

提前致谢。

解决方法

你怎么称呼道具?我可以让它在我的最后正常工作。我所做的是,将所有路径和坐标变量和值放在您返回的 <MyMapComponent/> 中,然后在 Map function 中调用它作为 const <MyMapComponent/>。每次我更改 props.variablename 中变量内的值时,更改也会反映在地图上。下面是一个 sample code 和代码片段:

Map function