【发布时间】:2021-07-08 13:58:47
【问题描述】:
我正在使用 DirectionsRenderer react-google-maps 库来渲染两点之间的目的地。我想在 Map.js 文件中为起点和终点传递自定义道具, 这是我的代码;
import React from 'react'
import { withScriptjs } from "react-google-maps";
import Map from './Map'
const Directions = ({ origin, destination }) => {
const MapLoader = withScriptjs(props => <Map {...props} />);
return (
<div className="App">
<MapLoader
googleMapURL="https://maps.googleapis.com/maps/api/js?key="
loadingElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
export default Directions
Map.js
import React, { useEffect, useState } from "react";
import {
withGoogleMap,
GoogleMap,
DirectionsRenderer
} from "react-google-maps";
function Map({props}) {
const [directions, setDirections] = useState(null)
useEffect(() => {
const google = window.google
const directionsService = new google.maps.DirectionsService();
const origin = { lat: 23.6238, lng: 90.5000};
const destination = { lat: 23.8103, lng: 90.4125 }
directionsService.route(
{
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
console.log(result)
setDirections(result)
} else {
console.error(`error fetching directions ${result}`);
}
}
);
}, [])
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
defaultCenter={{ lat: 23.8103, lng: 90.4125 }}
defaultZoom={17}
>
<DirectionsRenderer
directions={directions}
/>
</GoogleMap>
));
return (
<div>
<GoogleMapExample
containerElement={<div style={{ height: `400px`, width: "500px" }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
export default Map;
在这里,我想从根路由(Directions.js)获取目的地和起点。 有人告诉我如何将其作为道具传递给 Map.js。
【问题讨论】:
标签: google-maps google-directions-api react-google-maps