[英]React.js dynamic map directions renderer
我一直想知道如何制作動態地圖路線/路線。 我正在使用此插件Directions Renderer,但這是一個靜態示例。 我只想使用我的輸入字段進行路由。
這是我的代碼:
/* 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}
/>
);
}
}
為了闡明您的問題,我個人使用
import PlacesAutocomplete from 'react-places-autocomplete';
import { geocodeByAddress, geocodeByPlaceId } from 'react-places
autocomplete';
這會創建一個不錯的自動填充字段。 我還使用下面的這兩個npm包來顯示我的地圖。
import Map, {GoogleApiWrapper} from 'google-maps-react'
import Marker from 'google-maps-react'
希望這可以以某種方式有所幫助,如果您需要使用這些軟件包的幫助,請告訴我,我可以展示一些示例,歡呼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.