繁体   English   中英

使用 react-google-maps 在 map 上渲染标记

[英]Render marker on map with react-google-maps

我正在尝试在谷歌 map 上加载一个标记,但我不知道该怎么做。 在文档中,它显示了下一个示例:

const MyMapComponent = compose(
  withProps({
     googleMapURL: "api key",
     loadingElement: <div style={{ height: `100%` }} />,
     containerElement: <div style={{ height: `400px` }} />,
     mapElement: <div style={{ height: `100%` }} />
  }),
  withScriptjs,
  withGoogleMap
  )(props => (
   <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
      {props.isMarkerShown && (
        <Marker position={{ lat: -34.397, lng: 150.644 }} />
      )}
   </GoogleMap>
  ));
  ReactDOM.render(<MyMapComponent isMarkerShown />, document.getElementById("root"));

但我实际上想做的是创建 map 组件并在另一个组件中调用它。 map 在我调用它时加载正常,但我的问题是:如何将标记传递给我调用 map 的组件?

这是我的 map 组件:

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

const MyMapComponent = compose(
 withProps({
    googleMapURL:
        "api key",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
 }),
 withScriptjs,
 withGoogleMap
 )(props => (
   <GoogleMap defaultZoom={15} defaultCenter={{ lat: 46.802681, lng: 23.764006 }}>
    {props.isMarkerShown && (
        <Marker position={{ lat: 46.802681, lng: 23.764006 }} />
    )}
   </GoogleMap>
 ));

 export default MyMapComponent;

然后我在另一个组件中调用它,如下所示:

import MyMapComponent from './myMap';
const Contact = () => {
   return (
    <div class="contact">
        <MyMapComponent />
    </div>
   )
}

在您的Contact组件中,同时返回MyMapComponent传递道具isMarkerShown作为您在 Map 组件中定义它的方式,因为它需要道具isMarkerShown来呈现标记,如果您想将动态坐标传递给它,您可以在您的联系人组件:

import MyMapComponent from './myMap';
const Contact = () => {
 return (
   <div class="contact">
      <MyMapComponent isMarkerShown lat={49.076} lng={42.8777} />
  </div>
  )
}

在您的 Map 组件中:

import React from "react";
.
.

const MyMapComponent = compose(
  withProps({
    googleMapURL:"API Key",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
   )},
  withScriptjs,
  withGoogleMap
 )(props => (
    <GoogleMap defaultZoom={15} 
               defaultCenter={{ lat: props.lat, lng: props.lng }}>
        {props.isMarkerShown && (
           <Marker position={{ lat: props.lat, lng: props.lng }} />
       )}
   </GoogleMap>
 ));

export default MyMapComponent;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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