Google-Map-React, как получить маркеры внутри границ? - PullRequest
0 голосов
/ 24 апреля 2018

У меня есть границы при перемещении карты, но я понятия не имею, как получить маркеры, содержащиеся в этих границах.Я не хочу использовать new google.map....Я хотел бы продолжать использовать только React-Google-Map.Если это невозможно, я буду использовать экземпляр Google.

Я опубликую свой код ниже.Я консоль, выходя из ссылки на карту Google и реквизиты внутри функции onChange.

Props => 

bounds:{nw: {…}, se: {…}, sw: {…}, ne: {…}}
center:{lat: 53, lng: -7.77000000000001}
marginBounds:{nw: {…}, se: {…}, sw: {…}, ne: {…}}
size:{width: 1818, height: 455}
zoom:10
__proto__:Object

Map Ref => GoogleMap {props: {…}, context: {…}, refs: {…}, updater: {…}, _getMinZoom: ƒ, …}

import React, { Component } from 'react';
import GoogleMap from 'google-map-react';

function findMarkerIndex(id, markers) {
  for (let i = markers.length; i--; ) {
    if (markers[i].id === id) {
      return i;
    }
  }
  return null;
}

export default class Map extends Component {
  constructor(props) {
    super(props);
    this.createMapOptions = this.createMapOptions.bind(this);
    this.changeMap = this.changeMap.bind(this);
    this.toggleMarker = this.toggleMarker.bind(this);

    this.state = {
      markers: []
    };
  }

  changeMap(props) {
    console.log(props);
    console.log(this.map);
  }

  toggleMarker(id) {
    const index = findMarkerIndex(id, this.state.markers);
    if (index !== null) {
      const markers = this.state.markers;
      markers[index].show = !markers[index].show;
      this.setState({ markers });
    }
  }

  closeMarker(id) {
    const index = findMarkerIndex(id, this.state.markers);
    if (index !== null) {
      const markers = this.state.markers;
      markers[index].show = false;
      this.setState({ markers });
    }
  }

  createMapOptions(maps) {
    return {
      styles: this.props.styles
    };
  }

  componentDidMount() {
    this.setState({ markers: this.props.markers });
  }

  render() {
    const Marker = this.props.markerComponent;
    const markers = (this.state.markers || []).map(marker => (
      <Marker
        key={marker.id}
        handleMarkerClick={this.toggleMarker}
        handleMarkerClose={this.closeMarker}
        {...marker}
      />
    ));
    return (
      <div
        style={{
          height: this.props.height || '800px',
          width: this.props.width || '100%'
        }}
      >
        <GoogleMap
          ref={ref => {
            this.map = ref;
          }}
          center={this.props.center || { lat: 50, lng: 25 }}
          zoom={this.props.zoom || 8}
          options={this.createMapOptions || {}}
          onChange={this.changeMap}
        >
          {markers}
        </GoogleMap>
      </div>
    );
  }
}

Ответы [ 2 ]

0 голосов
/ 24 апреля 2018

Не уверен, что это "лучший" способ, но я немного взломал это, просто используя границы метода onChange.

Я взял все границы и сравнил их с моим маркером.Я опубликую то, что я сделал, и это, кажется, работает просто отлично.Если у него есть недостатки, пожалуйста, дайте мне знать!

changeMap(props) {
    const {
      bounds: { ne, nw, se, sw }
    } = props;
    // east for lng will be greater
    // north for lat will be greater
    const { markers } = this.state;
    if (markers) {
      markers.map(marker => {
        if (
          marker.lat > se.lat &&
          sw.lat &&
          (marker.lat < ne.lat && nw.lat) &&
          (marker.lng > nw.lng && sw.lng) &&
          (marker.lng < ne.lng && se.lng)
        ) {
          console.log(marker);
        }
      });
    }
  }
0 голосов
/ 24 апреля 2018

Контролируя маркеры, помещаемые на карту (this.state.markers), вы можете просто .filter() пробегать их, используя имеющиеся у вас границы.

const { markers } = this.state;
if (markers) {
  const foundMarkers = markers.filter(marker => {
    if (
      marker.lat > se.lat &&
      sw.lat &&
      (marker.lat < ne.lat && nw.lat) &&
      (marker.lng > nw.lng && sw.lng) &&
      (marker.lng < ne.lng && se.lng)
    ) {
      return marker;
    }
  });
console.log(foundMarkers);

}
...