Я использую собственные карты реакции - Mapview в моем приложении React Native. На Android код работает должным образом, местоположение пользователя используется для определения региона. Это будет включено в this.state.latitude и this.state.lontitude. Только на iOS у меня проблема в том, что когда я «прокручиваю» карту, она переходит обратно в регион после освобождения. Если я помещу код в initialRegion, я окажусь где-нибудь в море, и пользователь должен прокручивать бесконечно. У кого-нибудь есть опыт с этим?
после установки кода в initialRoute:
Текущий код:
import React, {Component} from 'react';
import {StyleSheet, Text, View,ScrollView, SafeAreaView, ImageBackground, Button,TouchableOpacity, Alert, Image, Linking, ActivityIndicator} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { ListItem, ThemeConsumer } from 'react-native-elements'
import { Marker, PROVIDER_GOOGLE } from "react-native-maps";
//import { ClusterMap } from "react-native-cluster-map";
import MapView from "react-native-map-clustering";
import firebase from 'react-native-firebase';
import Geolocation from '@react-native-community/geolocation';
import LaunchNavigator from 'react-native-launch-navigator';
if(Platform.OS === "android") LaunchNavigator.setGoogleApiKey("API KEY");
class locationScreen extends Component {
constructor(props){
super(props);
this.state = {
cities : [ ],
totalStores: 0,
latitude:0,
longitude: 0,
nearestPlace: null,
}
}
deg2Rad = (deg) => {
return deg * Math.PI / 180;
}
pythagorasEquirectangular = (lat1, lon1, lat2, lon2) => {
lat1 = this.deg2Rad(lat1);
lat2 = this.deg2Rad(lat2);
lon1 = this.deg2Rad(lon1);
lon2 = this.deg2Rad(lon2);
const R = 6371;
const x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
const y = (lat2 - lat1);
const d = Math.sqrt(x * x + y * y) * R;
return d;
}
nearestCity = (latitude, longitude) => {
let mindif = 99999;
let closest;
for (let index = 0; index < this.state.cities.length; index++) {
const dif = this.pythagorasEquirectangular(latitude, longitude, this.state.cities[index].lat,
this.state.cities[index].long);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
this.setState({
nearestPlace: closest,
})
this.state.cities.forEach(i =>{
if( i.name == this.state.cities[this.state.nearestPlace].name) i.nearest = 1 ;
})
this.setState({
cities: this.state.cities,
})
// this.nearestPlace = closest
// return cities= closest;
}
navigateTo = (item) => {
console.log(item.street);
LaunchNavigator.navigate(item.street + "," + item.zip+ ","+ item.city)
.then(() => console.log("Launched navigator"))
.catch((err) => console.error("Error launching navigator: "+err));
}
setCurrentDirections = () =>{
Geolocation.getCurrentPosition(position => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
desLat: position.coords.latitude,
desLong: position.coords.longitude,
error: null,
});
console.log("reached function");
console.log("latitude: " + this.state.latitude);
console.log("Longtitude: " + this.state.longitude);
})
}
setNearestonClick= (clickId) =>{
this.state.cities.forEach(i =>{
if( i.name == clickId) i.nearest = 1 ;
})
this.setState({
cities: this.state.cities,
})
}
onItemClickHandler= (url)=>{
Linking.openURL(url)
}
/* PressedLocation = (data) =>{
console.log('location:' + data.lat + 'long ' +data.long );
this.setState({
latitude: data.lat,
longitude: data.long,
error: null,
});
}
*/
markerCliked = (id) =>{
console.log("id is: " + id);
}
latitude= 0;
longitude= 0;
componentDidMount(){
this.setCurrentDirections();
let ref = firebase.database().ref('stores');
ref.on('value' , snapshot =>{
var state = snapshot.val();
this.setState({
cities: state,
totalStores: state.length,
})
this.nearestCity(this.state.latitude, this.state.longitude);
})
}
render(){
const { cities } = this.state;
return(
<ScrollView style={styles.scorllVert}>
<SafeAreaView style={styles.container}>
<View style={styles.headerLeft}>
<TouchableOpacity style={styles.menubar} onPress={this.props.navigation.openDrawer}>
<Icon name="bars" size={24}/>
</TouchableOpacity>
</View>
<View style={styles.headerCenter}>
<Image source={require('./assets/images/all/logo-snackpoint.png')} style={styles.logoSnackpoint} />
</View>
<View style={styles.headerRight}>
<TouchableOpacity style={styles.userIcon}>
<Icon name="user-circle" size={24} onPress={this.props.navigation.openDrawer}/>
</TouchableOpacity>
</View>
</SafeAreaView>
<View style={styles.headerStores}>
<Text style={styles.headerStoresText}>Aantal vestigingen: {this.state.totalStores}</Text>
</View>
<View style={styles.containerContent}>
<View style={styles.page}>
<View style={styles.containerMap}>
<MapView
showsUserLocation={true}
style={{ flex: 1 }}
onClusterPress={() => this.markerCliked()}
region={{
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: 0.015,
longitudeDelta: 0.0121
}}
>
{
this.state.cities.map(marker => (
<Marker key={marker.name} coordinate={{latitude: marker.lat, longitude: marker.long}} onPress={() => this.setNearestonClick(marker.name)}/>
))
}
</MapView>
</View>
</View>
<View style={styles.stores}>
{
this.state.cities.sort(function(a, b) {
if(a.nearest) return -1;
if(b.nearest) return 1;
if(a.name.toLowerCase() < b.name.toLowerCase()) return -1;
if(a.name.toLowerCase() > b.name.toLowerCase()) return 1;
return 0;
}).map((marker, i) => (
<TouchableOpacity onPress={() => this.navigateTo(marker)} >
<View style={styles.store}>
<View style={styles.leftcolumn}>
<Text style={styles.storeTitle}>{marker.name}</Text>
<Text>{marker.street}</Text>
<Text>{marker.zip}, {marker.city}</Text>
<Text>Telefoon: {marker.phone}</Text>
</View>
<View style={styles.midcolumn}>
<Text>Ma:</Text>
<Text>Di:</Text>
<Text>Wo:</Text>
<Text>Do:</Text>
<Text>Vr:</Text>
<Text>Za:</Text>
<Text>Zo:</Text>
</View>
<View style={styles.rightcolumn}>
<Text>{marker.monday}</Text>
<Text>{marker.tuesday}</Text>
<Text>{marker.wednesday}</Text>
<Text>{marker.thursday}</Text>
<Text>{marker.friday}</Text>
<Text>{marker.saturday}</Text>
<Text>{marker.sunday}</Text>
</View>
</View>
<View style={{borderBottomColor: '#C8C8C8',borderBottomWidth: 1,}}/>
</TouchableOpacity>
))
}
</View>
</View>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start',
marginBottom: 13
},
text:{
color: "#161924",
fontSize: 20,
fontWeight: "500",
},userIcon:{
paddingTop: 22,
paddingRight: 0,
alignItems: 'flex-end',
},
logoSnackpoint:{
width: 180,
height: 52,
marginTop: 12,
},
headerLeft:{
width: '33%',
},
headerCenter:{
width: '30%',
alignItems: 'center',
},
headerRight:{
width: '30%',
},
menubar:{
paddingTop: 22,
paddingLeft: 20
},
containerContent:{
padding: 0,
paddingBottom: 30
},
title:{
fontSize: 35
},
textTitle:{
marginTop: 10,
},
titleRed:{
fontSize: 25,
color: '#CC2929',
marginTop: 30,
marginBottom: 10
},
map: {
flex: 1
},
page: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
containerMap: {
height: 300,
width: '100%',
backgroundColor: "tomato"
},
headerStores:{
width: '100%',
backgroundColor: '#CD2929',
textAlign: 'center',
paddingTop: 20,
paddingBottom: 20
},
headerStoresText:{
color: 'white',
textAlign: 'center'
},
store:{
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start',
width: '100%',
padding: 20
},
leftcolumn:{
width: "50%",
},
midcolumn:{
width: "20%",
},
rightcolumn:{
width: "30%",
},
storeTitle:{
color: '#CD2929',
fontWeight: "bold",
fontSize: 30
},
hr:{
backgroundColor: 'grey',
padding: 5
}
});
export default locationScreen;