reactjs - 如何在我的项目中实现 react-google-maps DirectionsRenderer
问题描述
我正在构建一个简单的项目,如果用户单击一个按钮,它应该显示从用户位置到我标记的目的地的方向。这是我的代码。我刚刚实现了一些部分,但我不明白如何实现 DirectionsRenderer,也无法从文章、文档中学习。现在我不知道该怎么办。谁能用更简单的方式解释我?谢谢!
GoogleMap,
withGoogleMap,
withScriptjs,
DirectionsRenderer,
} from 'react-google-maps';
import Marker from 'react-google-maps/lib/components/Marker';
function Map() {
return (
<div className='App'>
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: 51.507351, lng: -0.127758 }}
>
<Marker position={{ lat: 51.4666, lng: -0.213 }} />
</GoogleMap>
</div>
);
}
const DirectionsService = new window.google.maps.DirectionsService();
DirectionsService.route({
origin: new window.google.maps.LatLng(41.85073, -87.65126),
destination: new window.google.maps.LatLng(41.85258, -87.65141),
travelMode: window.google.maps.TravelMode.DRIVING,
});
const WrappedMap = withScriptjs(withGoogleMap(Map));
function App() {
return (
<div style={{ width: '100vw', height: '100vh' }}>
<WrappedMap
googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${process.env.REACT_APP_MAP_KEY}`}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `100%` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
export default App;
解决方案
以下是我为实现您的用例而采取的步骤:
- 使用浏览器
HTML5 Geolocation feature
获取用户在componentDidMount
. - 然后使用状态变量来保存当前位置的值。您还将用户当前位置状态的值放入对象的
center
参数中,GoogleMap
以便地图将显示用户所在的地图区域。这将用作origion
您的路线服务。3.还使用另一个状态来保存用户当前位置。这将用作在用户当前位置放置标记的状态。 onClick
在对象的参数中调用一个函数GoogleMap
。然后使用另一个状态变量来保存单击坐标的值。这将用作destination
方向服务的。- 在您的地图 div 顶部放置一个按钮并在其
OnClick
参数中调用一个函数。该函数将调用GoogleMaps directionsService
并计算您的起点和终点之间的路线。如果有路线,您可以使用另一个状态变量来保存路线服务的结果。 - 使用
DirectionsRenderer
GoogleMap 对象内的对象来显示路线的折线。
这是示例代码(注意:确保将您的 API 密钥放在 index.js 中以使示例正常工作)和下面的代码片段:
/*global google*/
import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
import {
withGoogleMap,
Marker,
GoogleMap,
DirectionsRenderer
} from 'react-google-maps';
class Map extends Component {
state = {
directions: null,
markerPos: null,
centerMarker: null,
currentLocation: null
};
componentDidMount = () => {
navigator?.geolocation.getCurrentPosition(
({ coords: { latitude: lat, longitude: lng } }) => {
const pos = { lat, lng };
this.setState({ currentLocation: pos, centerMarker: pos });
}
);
};
onMapClick = e => {
this.setState({ markerPos: e.latLng });
};
getDirections = () => {
const directionsService = new google.maps.DirectionsService();
const origin = this.state.currentLocation;
const destination = this.state.markerPos;
if (origin !== null && destination !== null) {
directionsService.route(
{
origin: origin,
destination: 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}`);
}
}
);
} else {
console.log('Please mark your destination in the map first!');
}
};
render() {
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
defaultZoom={13}
center={this.state.currentLocation}
onClick={this.onMapClick}
>
{this.state.centerMarker !== null && (
<Marker position={this.state.centerMarker} label={'userloc'} />
)}
{this.state.markerPos !== null && (
<Marker position={this.state.markerPos} />
)}
{this.state.directions !== null && (
<DirectionsRenderer
directions={this.state.directions}
defaultOptions={{
suppressMarkers: true
}}
/>
)}
</GoogleMap>
));
return (
<div>
<Button onClick={this.getDirections}>Get Direction</Button>
<GoogleMapExample
containerElement={<div style={{ height: `500px`, width: '500px' }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default Map;
推荐阅读
- r - 如何在 fct_recode 中使用列表项
- ms-access - 子表单未正确填充的 MS Access 问题
- azure-devops - 如何跟踪 Azure devops 中的错误?
- javascript - 使用 gatsby-plugin-root-import 解析单元测试的路径
- python - Discord.py - 机器人不发送消息并且没有错误消息
- javascript - 无法使用 javascript 在 html 中设置选定的索引
- python - requests.get() 返回的 HTML 与我浏览器上的不同
- html - 带有方形 SVG 元素的 CSS 网格
- c++ - std::unordered_map 未按预期运行
- webpack - 带有 Nextjs 的 Webpack 用于 worker-loader 包