如何在React Native中实现高度定制化的地图和定位功能
import React, { useEffect, useRef } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
const CustomMapView = () => {
const mapView = useRef(null);
useEffect(() => {
mapView.current.animateCamera({
zoomLevel: 16,
center: {
latitude: 37.78825,
longitude: -122.4324,
},
});
}, []);
const handleLocationPermission = () => {
Geolocation.requestAuthorization();
Geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
mapView.current.animateCamera({
zoomLevel: 16,
center: {
latitude,
longitude,
},
});
},
(error) => console.log(error.message),
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
};
return (
<View style={styles.container}>
<MapView
ref={mapView}
provider={PROVIDER_GOOGLE}
style={styles.map}
showsUserLocation
/>
<Text onPress={handleLocationPermission}>
定位我在这里
</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
map: {
width: '100%',
height: '50%',
},
});
export default CustomMapView;
这段代码展示了如何在React Native应用中使用react-native-maps
库来创建一个定制的地图视图,并实现了一个简单的定位功能。代码使用了useRef
来获取地图的引用,并在组件挂载后使用useEffect
动画地图的相机到指定的地理坐标。同时,它提供了一个可点击的文本组件,用于请求定位权限并在允许后动画地图到用户的当前位置。
评论已关闭