2017-08-25 12 views
0

私は動的マップのルートを作成する方法を知りました。私はこのプラグインDirections Rendererを使用していますが、これは静的な例です。私は自分の入力フィールドを使ってルートを作成したいだけです。ここでReact.jsダイナミックマップルートレンダラー

は私のコードです:

 /* global google */ 
     import { default as React, Component,} from "react"; 
     import { withGoogleMap, GoogleMap, DirectionsRenderer,} from "../../../lib"; 

const DirectionsExampleGoogleMap = withGoogleMap(props => (
    <GoogleMap 
    defaultZoom={7} 
    defaultCenter={props.center} 
    > 
    {props.directions && <DirectionsRenderer directions={props.directions} />} 
    </GoogleMap> 
)); 

export default class DirectionsExample extends Component { 

constructor(props) { 
    super(props); 
    this.state = { 
     origin: '', 
     destination: '', 
    } 

    this.handleOrigin = this.handleOrigin.bind(this); 
    this.handleDestination = this.handleDestination.bind(this); 
} 

handleOrigin(event) { 
     event.preventDefault() 
     this.setState({origin: event.target.value}); 
    } 

handleDestination(event) { 
    event.preventDefault() 
    this.setState({destination: event.target.value}); 
} 

    componentDidMount() { 
    const DirectionsService = new google.maps.DirectionsService(); 

    DirectionsService.route({ 
     origin: new google.maps.LatLng(this.state.origin), 
     destination: new google.maps.LatLng(this.state.destination), 
     travelMode: google.maps.TravelMode.DRIVING, 
    }, (result, status) => { 
     if (status === google.maps.DirectionsStatus.OK) { 
     this.setState({ 
      directions: result, 
     }); 
     } else { 
     console.error(`error fetching directions ${result}`); 
     } 
    }); 
    } 

    render() { 
    return (
     <input type='text' value={this.state.origin} onChange= 
     {this.handleOrigin} /> 
     <input type='text' value={this.state.destination} onChange2= 
     {this.handleDestination}/> 
     <DirectionsExampleGoogleMap 
     containerElement={ 
      <div style={{ height: `100%` }} /> 
     } 
     mapElement={ 
      <div style={{ height: `100%` }} /> 
     } 
     center={this.state.origin} 
     directions={this.state.directions} 
     /> 
    ); 
    } 
} 

答えて

1

あなたの問題にいくつかの光を当てるために、私は個人的に素敵なオートコンプリートフィールドを作成し

import PlacesAutocomplete from 'react-places-autocomplete'; 
    import { geocodeByAddress, geocodeByPlaceId } from 'react-places 
    autocomplete'; 

を使用しています。また、以下の2つのnpmパッケージを使用してマップを表示します。

import Map, {GoogleApiWrapper} from 'google-maps-react' 
    import Marker from 'google-maps-react' 

これは何らかの形で役立ちます。これらのパッケージを使用する際の助けが必要な場合はお知らせください。私はいくつかの例を表示できます。

+0

そのnpmパッケージを使用して動的な方向/ルートを作成できますか?場所を入力してルートを表示します。 btw私は反応場所オートコンプリートも使用しています。 – Deee