react-google-maps обновление точек маршрута (Waypoints in directions)

179
01 апреля 2018, 21:50

Подскажите как реализовать событие по нажатию кнопки - обновление маршрута между пинами(маркерами), реализовал динамическое наполнение маркеров из json, также сделал кластеризацию их... У меня есть список, который содержит координаты маркеров, которые добавляю динамически по нажатию на маркеры... Но не получается сделать обновление после того как имею список... MarkerMap.js direction, здесь храню координаты, которые передаю в Map.js waypts. Для реализации использую react-google-maps

Map.js

import React, {PureComponent} from "react";
import dataJson from '../../test_buildings.json';
import MarkerMap from '../MarkerMap';
import {direction} from '../MarkerMap'; 
const { compose, withProps, withHandlers, lifecycle} = require("recompose");
const {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  DirectionsRenderer,
} = require("react-google-maps");
const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");
const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `600px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withHandlers({
    onMarkerClustererClick: () => (markerClusterer) => {
      const clickedMarkers = markerClusterer.getMarkers()
      console.log(`Current clicked markers length: ${clickedMarkers.length}`)
      console.log(clickedMarkers)
    },
  }),
  withScriptjs,
  withGoogleMap,
  lifecycle({
    componentWillMount() {
      const google = window.google
      const DirectionsService = new google.maps.DirectionsService();
      const DirectionsDisplay = new google.maps.DirectionsRenderer();
      const waypts = [];
        for (var i=0; i<direction.length; i++){
          waypts[i] = {location: new google.maps.LatLng(direction[i][0], direction[i][1])};
        }   
        console.log(waypts);
        DirectionsService.route({
          origin: new google.maps.LatLng(55.72790759, 37.47678995),
          destination: new google.maps.LatLng(55.735686, 37.587664),
          travelMode: google.maps.TravelMode.DRIVING,
          waypoints: waypts
       }, (result, status) => {
          if (status === google.maps.DirectionsStatus.OK) {
             this.setState({
                directions: result,
             });
          } else {
            console.error(`error fetching directions ${result}`);
          }
       });
    }
  })
)(props =>
  <GoogleMap
    defaultZoom={6}
    defaultCenter={{ lat: 55.754709, lng: 37.621521 }}
  >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      averageCenter
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map((marker, index) => (
        marker.latitude && marker.longitude ? 
        <MarkerMap
          key={index}
          id={marker.id} 
          position={{ lat: marker.latitude, lng: marker.longitude }}
          name={marker.name}
          type={marker.type.split('::')[1]}
          /> : null
      ))}
    </MarkerClusterer>
    {props.isOpen && props.directions && <DirectionsRenderer directions={props.directions} />}
    <button onClick={}>Обновить маршрут</button>
  </GoogleMap>
);

class Map extends PureComponent {
  componentWillMount() {
    this.setState({ markers: [] })
  }
  componentDidMount() {
        this.setState({ markers: dataJson.data });
  }
  render() {
    return (
      <div>
      <div className="left-sidebar">
      <p className="left-sidebar__header">Точки маршрута</p>
      <ul className="waypoints">
      </ul>
      </div>
      <div className="map">
      <MapWithAMarkerClusterer markers={this.state.markers}/>
      </div>      
    </div>
    )
  }
}
export default Map;

MarkerMap.js

import React, {Component} from 'react'; 
import { Marker, InfoWindow } from "react-google-maps";

export const direction = [];
class MarkerMap extends Component {
constructor(props){
    super(props);
    this.state = {
        isOpen: false
    }
}
handleToggleOpen = () => {
    this.setState({
        isOpen: true,
    });
}
handleToggleClose = () => {
    this.setState({
        isOpen: false
    });
}
addList = () => {
        if(direction.indexOf(this.props.name) === -1) {
            direction.push([this.props.position.lat, this.props.position.lng, this.props.name]) 
            const parent = document.querySelector(".waypoints");
            const li = document.createElement("li");
            const div = document.createElement("div");
            const p = document.createElement("p");
            const btn = document.createElement("button");
            parent.appendChild(li);
            li.appendChild(div);
            div.appendChild(p);
            div.appendChild(btn);
            p.className = "waypoints__text";
            p.innerHTML = this.props.name;
            btn.className = "waypoints__button_delete";
            btn.addEventListener("click", function(){
                li.remove();
                direction.splice(direction.indexOf(p.textContent), 1);
                console.log(direction);
            });
        }
}
render() {
return (
        <Marker
            id={this.props.id}
            position={{ lat: this.props.position.lat, lng: this.props.position.lng}}
            name={this.props.name}
            type={this.props.type}
            onClick={() => this.handleToggleOpen()}
        >
        {
        this.state.isOpen &&
         <InfoWindow onCloseClick={() => this.handleToggleClose()}>
            <div>
             <p style={{textAlign: "center", fontWeight: "bold"}}>{this.props.type}</p>
             <p>{this.props.name}</p>
             <button onClick={() => this.addList()}>Добавить</button>
             </div>
         </InfoWindow>
        }
        </Marker>
    )
}
}
export default MarkerMap;
READ ALSO
Раскрывающееся меню на чистом js

Раскрывающееся меню на чистом js

Можно ли на чистом js сделать меню (ну или что-то подобное), что будет раскрываться при щелчке по элементу и закрываться, при щелчке по любому...

180
Получить пользовательское слово в теге

Получить пользовательское слово в теге

В шаблоне вывода тегов (компонент K2) пытаюсь получить пользовательское поле с ценойВ результате либо массив пустой либо ошибка в foreach

155
insert into в php

insert into в php

Здравствуйте, подскажите пожалуйста как могу сделать запрос insert into в обычном стиле а не ооп

155