你好,开发社区!今天,我将向您展示如何使用react-native-maps-directions
在两个点之间获得估计的旅行时间。在创建与旅行或运动有关的应用程序时,这可能非常方便。
目录
- Introduction
- Setting up react-native-maps-directions
- Retrieving the Travel Time
- Complete Sample Code
- Conclusion
引言
首先,让我们安装必要的软件包:
npm install react-native-maps react-native-maps-directions
另外,您需要一个Google Maps Direction API密钥。您可以获得一个here。
setSETER反应本地映射方向
接下来,让我们设置基本配置以显示路由指导:
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
const App = () => {
const origin = {latitude: 37.7749, longitude: -122.4194}; // For example, San Francisco
const destination = {latitude: 34.0522, longitude: -118.2437}; // For example, Los Angeles
return (
<MapView
style={{flex: 1}}
initialRegion={{
latitude: 36.7783,
longitude: -119.4179,
latitudeDelta: 10,
longitudeDelta: 10,
}}>
<MapViewDirections
origin={origin}
destination={destination}
apikey="YOUR_GOOGLE_MAPS_API_KEY"
/>
</MapView>
);
};
驱动旅行时间
react-native-maps-directions
提供了onReady
属性,该属性为加载路由信息时设置了回调。我们可以使用它来获得路线的距离和估计的旅行时间。
const handleDirectionsReady = (result) => {
const distance = result.distance; // Distance (km)
const duration = result.duration; // Travel time (hours)
console.log(`Distance: ${distance} km, Travel time: ${duration} hours`);
};
<MapViewDirections
...
onReady={handleDirectionsReady}
/>
complete示例代码
这是显示路线指导并检索旅行时间的完整示例代码:
import React from 'react';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
const App = () => {
const origin = {latitude: 37.7749, longitude: -122.4194};
const destination = {latitude: 34.0522, longitude: -118.2437};
const handleDirectionsReady = (result) => {
const distance = result.distance;
const duration = result.duration;
console.log(`Distance: ${distance} km, Travel time: ${duration} hours`);
};
return (
<MapView
style={{flex: 1}}
initialRegion={{
latitude: 36.7783,
longitude: -119.4179,
latitudeDelta: 10,
longitudeDelta: 10,
}}>
<MapViewDirections
origin={origin}
destination={destination}
apikey="YOUR_GOOGLE_MAPS_API_KEY"
onReady={handleDirectionsReady}
/>
</MapView>
);
};
export default App;
结论
在本文中,我们探索了如何使用react-native-maps-directions
在两个点之间检索估计的旅行时间。在构建与旅行相关的应用程序时,此方法可以简化该过程。尝试一下并增强您的应用程序!
如果您发现这有用,请留下类似或评论。请继续关注更多有用的教程! ð