如何使用react-google-maps显示多个标记

问题描述 投票:0回答:6

我正在尝试使用名为react-google-maps的npm包显示多个标记,但我遇到了困难。我在这里关注如何显示一个地图标记的演示(https://tomchentw.github.io/react-google-maps/events/simple-click-event),但是当我做一件简单理解的事情时向 GoogleMap 组件添加第二个标记元素时,我无法显示该标记(我还更改了坐标)。这真的很困扰我,如果有人能指出出了什么问题,我将非常感激。

谢谢。

这是我摆弄过的代码。 我唯一改变的是添加第二个标记和新坐标。

/* global google */
import {
  default as React,
  Component,
} from "react";


import withGoogleMap from './assets/withGoogleMap';
import GoogleMap from './assets/GoogleMap';
import Marker from './assets/Marker';

const SimpleClickEventExampleGoogleMap = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapMounted}
    zoom={props.zoom}
    center={props.center}
    onCenterChanged={props.onCenterChanged}
  >
    <Marker
      defaultPosition={props.center}
      title="Click to zoom"
      onClick={props.onMarkerClick}
    />

    <Marker
      defaultPosition={props.marker2center}
      title="Click to zoom"
      onClick={props.onMarkerClick}
    />



  </GoogleMap>
));

const INITIAL_CENTER = { lat: -25.363882, lng: 131.044922 };
const MARKER1_CENTER = { lat: -25.363882, lng: 131.044922 };
const MARKER2_CENTER = { lat: -25.44, lng: 131.55 };

/*
 * https://developers.google.com/maps/documentation/javascript/examples/event-simple
 *
 * Add <script src="https://maps.googleapis.com/maps/api/js"></script> to your HTML to provide google.maps reference
 */
export default class SimpleClickEventExample extends Component {



  state = {
    zoom: 4,
    center: INITIAL_CENTER,
    marker2center: MARKER2_CENTER
  };

  handleMapMounted = this.handleMapMounted.bind(this);
  handleCenterChanged = this.handleCenterChanged.bind(this);
  handleMarkerClick = this.handleMarkerClick.bind(this);

  handleMapMounted(map) {
    this._map = map;
  }

  handleMarkerClick() {
    this.setState({
      zoom: 8,
    });
  }

  handleCenterChanged() {
    const nextCenter = this._map.getCenter();
    if (nextCenter.equals(new google.maps.LatLng(INITIAL_CENTER))) {
      // Notice: Check nextCenter equality here,
      // or it will fire center_changed event infinitely
      return;
    }
    if (this._timeoutId) {
      clearTimeout(this._timeoutId);
    }
    this._timeoutId = setTimeout(() => {
      this.setState({ center: INITIAL_CENTER });
      this._timeoutId = null;
    }, 3000);

    this.setState({
      // Because center now is a controlled variable, we need to set it to new
      // value when "center_changed". Or in the next render it will use out-dated
      // state.center and reset the center of the map to the old location.
      // We can never drag the map.
      center: nextCenter,
    });
  }

  componentWillUnmount() {
    if (this._timeoutId) {
      clearTimeout(this._timeoutId);
    }
  }

  render() {
    return (
      <div className='googleMap' style={{width: "500px", height: "500px", margin: "0 auto"}}>
        <SimpleClickEventExampleGoogleMap
          containerElement={
            <div style={{ height: `100%` }} />
          }
          mapElement={
            <div style={{ height: `100%` }} />
          }
          zoom={this.state.zoom}
          center={this.state.center}
          onMapMounted={this.handleMapMounted}
          onCenterChanged={this.handleCenterChanged}
          onMarkerClick={this.handleMarkerClick}
        />
      </div>
    );
  }
}
javascript google-maps reactjs google-maps-api-3 maps
6个回答
6
投票

要显示多个标记,您所要做的就是在具有标记位置的数组中进行迭代。

{marks.map((mark, index) => <Marker key={index} position={mark} />)}

这是一个具有更多功能的解决方案。每当用户单击该代码片段时,该代码片段就会在地图上添加多个圆圈。

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

const Map = withScriptjs(
    withGoogleMap(props => (
        <GoogleMap
            defaultZoom={12}
            defaultCenter={{ lat: -34.397, lng: 150.644 }}
            onClick={e => props.onMapClick(e)}
        >
            {props.marks.map((mark, index) => (
                <Circle
                    key={index}
                    center={mark}
                    radius={1000}
                    options={{
                        strokeColor: "#66009a",
                        strokeOpacity: 0.8,
                        strokeWeight: 2,
                        fillColor: `#66009a`,
                        fillOpacity: 0.35,
                        zIndex: 1
                    }}
                />
            ))}
        </GoogleMap>
    ))
);

class ReportsPage extends Component {
    state = {
        marks: []
    };

    setMark = e => {
        this.setState({ marks: [...this.state.marks, e.latLng] });
    };

    deleteMarkS = () => {
        this.setState({
            marks: []
        });
    };

    render() {
        const { marks } = this.state;
        return (
            <div>
                <button onClick={this.deleteMark}>DELETE MARKS</button>
                <Map
                    googleMapURL="http://maps.googleapis.com/maps/api/js?key=[YOUR GOOGLE MAPS KEY]"
                    loadingElement={<div style={{ height: `100%` }} />}
                    containerElement={<div style={{ height: `400px` }} />}
                    mapElement={<div style={{ height: `100%` }} />}
                    onMapClick={this.setMark}
                    marks={marks}
                />;
            </div>
        );
    }
}

export default ReportsPage;

不要忘记将 [您的 GOOGLE 地图密钥] 更改为您真正的密钥。


5
投票

您需要将一组标记作为子级传递给

GoogleMap
组件并像这样映射它们:

<GoogleMap>
{props.markers.map(marker => (
    <Marker
      position={{ lat: marker.latitude, lng: marker.longitude }}
      key={marker.id}
    />
))}
</GoogleMap>

查看更多信息https://github.com/tomchentw/react-google-maps#withgooglemaphttps://tomchentw.github.io/react-google-maps/addons/marker-clusterer


2
投票

我认为你忘记在

marker2center
组件中传递
SimpleClickEventExampleGoogleMap
属性。

看一下

marker2center={this.state.marker2center}

<SimpleClickEventExampleGoogleMap
  containerElement={
    <div style={{ height: `100%` }} />
  }
  mapElement={
    <div style={{ height: `100%` }} />
  }
  zoom={this.state.zoom}
  center={this.state.center}
  marker2center={this.state.marker2center}
  onMapMounted={this.handleMapMounted}
  onCenterChanged={this.handleCenterChanged}
  onMarkerClick={this.handleMarkerClick}
/>

当然,如果您要使用一千个标记,您可以使用

map
,这样您就不需要手动将每个标记放入地图中。

稍微改变一下就会像这样:

<SimpleClickEventExampleGoogleMap
  containerElement={
    <div style={{ height: `100%` }} />
  }
  mapElement={
    <div style={{ height: `100%` }} />
  }
  zoom={this.state.zoom}
  center={this.state.center}
  markers={[MARKER1_CENTER, MARKER2_CENTER]}
  onMapMounted={this.handleMapMounted}
  onCenterChanged={this.handleCenterChanged}
  onMarkerClick={this.handleMarkerClick}
/>

const SimpleClickEventExampleGoogleMap = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapMounted}
    zoom={props.zoom}
    center={props.center}
    onCenterChanged={props.onCenterChanged}
  >
    {props.markers.map((marker, index)=> {
      return (
        <Marker
          position={marker}
          title="Click to zoom"
          onClick={props.onMarkerClick}
        />
      )
    })}
  </GoogleMap>
));

1
投票

我在我的代码中使用了它,幸运的是它有效!

/* global google */
import React, { Component } from 'react';
import {
    withScriptjs,
    withGoogleMap,
    GoogleMap,
    Marker,
    InfoWindow
} from 'react-google-maps';
import { compose, withProps } from 'recompose';

let markers=[
    {
        id:1,
        latitude: 25.0391667,
        longitude: 121.525,
        shelter:'marker 1'

    },
    {
        id: 2,
        latitude: 24.0391667,
        longitude: 110.525,
        shelter: 'marker 2'

    },
    {
        id: 3,
        latitude: 20.0391667,
        longitude: 100.525,
        shelter: 'marker 3'

    }
]
const MapWithAMarkerClusterer = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `100%` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap
)(props =>
    <GoogleMap
        defaultZoom={2}
        defaultCenter={{ lat: 25.0391667, lng: 121.525 }}
    >
        {markers.map(marker => {
            //const onClick = props.onClick.bind(this, marker)
            return (
                <Marker
                    key={marker.id}
                   
                    position={{ lat: marker.latitude, lng: marker.longitude }}
                >
                    <InfoWindow>
                        <div>
                            {marker.shelter}
                        </div>
                    </InfoWindow>
                </Marker>
            )
        })}
    </GoogleMap>
);

class googleMap extends Component {

    render() {
        return (
            <MapWithAMarkerClusterer />
        )
    }
}
export default googleMap;

0
投票

既然人们使用地图来显示标记(我也这样做了),那么你打算如何为他们显示路线?请帮助我。


-3
投票

停止处理

react-google-map
。有更好的(有更好的社区)包。 检查
google-map-react
包装。 我实现了这个包,它非常容易使用:https://github.com/BrodaNoel/devseverywhere/blob/master/src/containers/Metrics/index.jsx

编辑: 如果链接失效了,只需在整个项目中搜索

GoogleMapReact
即可。

© www.soinside.com 2019 - 2024. All rights reserved.