1 回答
TA貢獻1810條經驗 獲得超5個贊
我通過復制和改編來自官方世博會文檔https://docs.expo.io/versions/v35.0.0/sdk/location/的示例解決了這個問題
import React, { useState, useEffect } from "react";
import { StyleSheet, Platform } from "react-native";
import { useSelector } from "react-redux";
import MapView, { Marker } from "react-native-maps";
import Constants from "expo-constants";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
const MapScreen = props => {
const availableVenues = useSelector(state => state.cafes.availableVenues);
const [isLocation, setLocation] = useState(null);
const [mapRegion, setMapRegion] = useState({
region: {
latitude: -37.813629,
longitude: 144.963058,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}
});
const selectItemHandler = (id, title) => {
props.navigation.navigate("VenueDetail", {
venueId: id,
venueTitle: title
});
};
useEffect(() => {
if (Platform.OS === "android" && !Constants.isDevice) {
Alert.alert(
"Error",
"Oops, this will not work on Sketch in an Android emulator. Try it on your device!",
[
{
text: "Okay"
}
]
);
} else {
this._getLocationAsync();
}
}, []);
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
Alert.alert(
"Insufficient Permissions",
"Sorry, we need location permissions to make this work!",
[
{
text: "Okay"
}
]
);
}
let location = await Location.getCurrentPositionAsync({});
setLocation({ location });
setMapRegion({
region: {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}
});
console.log(mapRegion);
};
return (
<MapView
style={styles.map}
showsUserLocation={true}
initialRegion={mapRegion.region}
region={mapRegion.region}
>
{availableVenues.map(marker => (
<Marker
key={marker.id}
coordinate={{ latitude: marker.lat, longitude: marker.lng }}
title={marker.title}
description={marker.address}
onPress={() => { //Need to change to press popup
setTimeout(() => {
selectItemHandler(marker.id, marker.title);
}, 5000);
}}
/>
))}
</MapView>
);
};
MapScreen.navigationOptions = {
headerTitle: "Venue Map"
};
const styles = StyleSheet.create({
map: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1"
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: "center",
color: "black"
}
});
export default MapScreen;
添加回答
舉報
