/** * @format * @flow */ import React, {Component} from 'react'; import { Platform, StyleSheet, Text, TouchableWithoutFeedback, View, TextInput, Animated, Dimensions, Image, PermissionsAndroid, AsyncStorage, StatusBar, TouchableNativeFeedback, TouchableOpacity,BackHandler,Alert,ProgressBarAndroid , FlatList } from 'react-native'; import IMap from './IMap' import ActionButton from 'react-native-action-button'; import {CardView} from "react-native-cardview" import {responsiveHeight,responsiveWidth,} from 'react-native-responsive-dimensions'; import { material } from 'react-native-typography'; import {getMakersFrom,loadGroupeAgent,getPositionInformation} from './../../webservice/MapService'; import {readUser,getCountryNetwork,getPasObject} from './../../webservice/AuthApi' import BaseScreen from './../BaseScreen' import isEqual from 'lodash/isEqual'; import Button from 'apsl-react-native-button' import I18n from 'react-native-i18n' import Configuration from "../../webservice/persistences/Configuration"; import {MaterialDialog} from "react-native-material-dialog"; import { ProgressDialog,Dialog } from 'react-native-simple-dialogs'; const countries=require("./../../utils/country_code.json") import SnapSlider from 'react-native-snap-slider' import call from "react-native-phone-call"; import Icon from 'react-native-vector-icons/MaterialIcons'; import Geolocation from 'react-native-geolocation-service'; let geolib=require("geolib") require('./../../utils/Translations') import InterticielAds from './../ads/InterticielAds' import SnackBar from 'react-native-snackbar-component' const GEOLOCATION_OPTIONS = { enableHighAccuracy: true, timeout: 20000, maximumAge: 500,useSignificantChanges:false,distanceFilter:0 }; const radioOptions=[{label:"mon Reseau",value:0},{label:"Tout",value:1}] const theme=require('./../../utils/theme.json'); const route=require('./../../route.json'); import {FAB,Card,Surface} from 'react-native-paper' import BottomSheet from 'reanimated-bottom-sheet' const { width: viewportWidth, height: viewportHeight } = Dimensions.get('window'); import MarkerManager from './../../webservice/persistences/MarkerManager' const slideHeight=responsiveHeight(30)>270?270:responsiveHeight(30) //var Fabric = require('react-native-fabric'); //var { Crashlytics } = Fabric const defaultProps = { enableHack: false, geolocationOptions: GEOLOCATION_OPTIONS, }; class Home extends BaseScreen { static navigationOptions =({navigation}) =>{ return { headerMode:"none", headerStyle:{ display:'none' }, header:null, drawerLabel: navigation.getParam("name",I18n.t('MAP')), drawerIcon: ({ tintColor }) => ( ), }}; static defaultProps = { draggableRange: { top: responsiveHeight(30), bottom: 0 }, panel: null }; _draggedValue = new Animated.Value(0) renderIcon = icon => ({ isActive }) => ( ) onLoadMore() { const {user, prevRegion,boundarie} = this.state if (user.category === undefined || user.category === null) { if (this.promiseRegion) this.promiseRegion.done() this.promiseRegion = new Promise(async (resolve, reject) => { this.setState({isNeedLoadMore: false, isLoadingMap: true}) const camera = await this.mapRef.getCamera() const zoom = camera.zoom - 10 let res = [] this.setState({isLoadingMap: true}) if (this.state.filternetworkTemp !== undefined) { let net = this.state.filternetworkTemp.id res = this.state.networks.filter(function (item) { return item.id === net }) } if (res.length > 0) { let reseau = res[0]; const pos = {longitude: user.longitude, latitude: user.latitude} try { //let data = await loadMarkers(pos, reseau, 5000, this.state.page) let data=await this.loadingMarkers(this.state.myPosition,this.state.filternetwork,this.state.value) this.treatNewData(pos,data,false) } catch (e) { console.debug(e.message) this.setState({isNeedLoadMore: false, isLoadingMap: false}) } } else { this.setState({isNeedLoadMore: true, isLoadingMap: false}) } if(this.map)this.map.focusToUser() resolve() }) } } openDrawer = () => { this.props.navigation.openDrawer() } onslidingEvent(event) { this.setState({ maxHeightSliding: event.nativeEvent.layout.height }); } navigationEventListener _retrieveData = async () => { try { const value = await AsyncStorage.getItem('position'); if (value !== null) { let re=JSON.parse(value) re.longitudeDelta=0.04 re.latitudeDelta=0.01 const pos=JSON.parse(value) this.setState({region:re,oldPosition:pos}) } } catch (error) { console.warn(error) } }; componentDidMount() { this.mounted = true; this.configuration=new Configuration() const { navigation } = this.props; this.markerManager=new MarkerManager() this.configuration.getCurrentPubValue().then((value)=>{ try{ const val=parseInt(value) this.setState({isPubShow:val}); }catch(e){ } }) this.focusListener = navigation.addListener("didFocus", () => { this.configuration.getCurrentPasValue().then((value)=>{ try{ this.setState({pas:parseInt(value)}); }catch(e){ } }) this.componentDidAppear() }); this.blurListener=navigation.addListener("didBlur",(payload)=>{ this.componentDidDisappear() }) this._retrieveData() //this.toggleSlidingUp(false) if (this.props.coordinate) return; } async requestCameraPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { 'title': 'Cool Photo App Camera Permission', 'message': 'Cool Photo App needs access to your camera ' + 'so you can take awesome pictures.' } ) if (granted === PermissionsAndroid.RESULTS.GRANTED) { readUser().then((user) => { if (user) { if (user.category !== undefined && user.category !== null) { const myPosition = { latitude: parseFloat(user.latitude), longitude: parseFloat(user.longitude) } const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition}); this.mapRef.animateToCoordinate({ latitude: myPosition.latitude, longitude: myPosition.longitude }, 1000) this.mapRef.animateToRegion(reg, 1000) this.setState({isLoading:false,isLoadingMap:false,loadingDialog:false}) if (user.category !== "geolocated") { this.showMyMembers(); } else { if (myPosition.latitude <= 0 && myPosition.longitude <= 0) { this.props.navigation.push(route.updateinfo); } } } else { this.getPosition() this.watchLocation(); } } }) console.log("Camera permission granted") } else { console.log("Camera permission denied") } } catch (err) { console.log(err) } } _storeData = async (position) => { try { await AsyncStorage.setItem('position', JSON.stringify(position)); } catch (error) { console.warn(error) } }; watchLocation() { this.watchID = Geolocation.watchPosition((position) => { const myLastPosition = this.state.myPosition; let myPosition = position.coords; const oldPosition=this.state.oldPosition if (!myLastPosition || (myPosition.longitude!==myLastPosition.longitude || myPosition.latitude!==myLastPosition.latitude)) { if(myPosition.longitude!==0 && myPosition.latitude!==0) this._storeData(myPosition) if(isEqual(this.state.region,{}) || isEqual(this.state.region,undefined) || isEqual(this.state.region,null)) if(!this.state.myPosition.longitude && !this.state.myPosition.latitude){ if (this.mapRef !== null && this.mapRef !== undefined) { this.mapRef.animateToRegion({ latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, }, 1000) this.mapRef.animateCamera({ center: this.myPosition, pitch: 0, heading: 0, altitude: 0, zoom: 12 }, 1000) } } this.setState({region: {latitude:myPosition.latitude,longitude:myPosition.longitude,latitudeDelta:0.003,longitudeDelta:0.004}}); this.setState({myPosition: myPosition}); if(this.map)this.map.focusToUser() } }, (error=>console.log("wat s",error)),GEOLOCATION_OPTIONS); } getNetworks(pays) { if (pays) { getCountryNetwork(pays).then((result) => { this.reseaux = []; let networks = result; for (let prop in networks) { this.reseaux.push(networks[prop]); } this.setState({networks: this.reseaux}); let c = this.reseaux.filter((item) => { return item.name.includes(this.state.network); }) if(this.state.user.category===undefined || this.state.user.category===null){ console.log(this.state.user) if (c.length > 0 && pays ) { this.setState({filternetwork: c[0], myNetwork: c[0],filternetworkTemp:c[0]}) this.retrieveAllPoint(pays) }else{ console.log("on getnetworks",result) if(this.state.user){ if(!this.state.user.category) Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ if(pays!==null && pays!==undefined) this.getNetworks(pays) else this.requestCameraPermission() }} ], {cancelable:false} ) } } } }, (err) => { console.log("error getnetwork"+e.message) // Crashlytics.log("get networks"+e.message) Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ if(pays!==null && pays!==undefined) this.getNetworks(pays) else this.requestCameraPermission() }} ], {cancelable:false} ) }) } else { console.log("get network missing pays") var msg = "impossible de récupérer le nom du pays"; Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.requestCameraPermission() }} ], {cancelable:false} ) } } getPosition(options=null) { console.log("on get position") Geolocation.getCurrentPosition( (position) => { const myLastPosition = this.state.myPosition; const myPosition = position.coords; const oldPosition=this.state.oldPosition if (!isEqual(myPosition, myLastPosition) && myPosition.longitude!==0 && myPosition.latitude!==0||myLastPosition ) { if(this.map)this.map.focusToUser() getPositionInformation(myPosition).then((response) => { if(response){ if (response.results !== undefined) { if (response.results.length > 0) { let most = response.results[0] let {address_components, formatted_address, place_id} = most this.setState({address: address_components, textadress: formatted_address, place: place_id}) let results = response.results; let shortcountry; let mcountry; for (let i = 0; i < results[0].address_components.length; i++) { for (let j = 0; j < results[0].address_components[i].types.length; j++) { if (results[0].address_components[i].types[j] === "country") { mcountry = results[0].address_components[i]; shortcountry = mcountry.short_name; this.setState({ shortCountry: mcountry.short_name, longCountry: mcountry.long_name }) } } } for (let i of countries) { if (i.code === shortcountry) { this.setState({indicatif: i.dial_code}) this.getNetworks(i.dial_code) } } } }else{ console.log("on else result null ") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.getPosition(options) }} ], {cancelable:false} ) } }else{ Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.getPosition(options) }} ], {cancelable:false} ) } }); const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition, region: reg}); if(this.mapRef && !this.state.myPositionIsAnimated) { this.mapRef.animateCamera({ center: myPosition, pitch: 0, heading: 0, altitude: 5, zoom: 13 }, 1000) this.setState({myPositionIsAnimated:true}) } }else console.warn("errror") }, (error) => { console.warn(error.message) switch(error.code){ case 3: if(this.state.oldPosition){ this.treatPosition(this.state.oldPosition) } break; default: //Crashlytics.log(error.message) console.log("onjjj",error.message) /* Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.getPosition(options) }} ], {cancelable:false} )*/ } }, GEOLOCATION_OPTIONS ); } componentDidDisappear() { BackHandler.removeEventListener('hardwareBackPress', this.backPressed); } componentDidAppear() { BackHandler.addEventListener('hardwareBackPress', this.backPressed); // this.props.start(); readUser().then((user) => { if (user) { if(user.category){ this.setState({user: user}) this.setState({network: user.network}); const myPosition = { latitude: parseFloat(user.latitude), longitude: parseFloat(user.longitude) } const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition}); } if(this.state.myPosition) this.refocusMap() /*if (Platform.OS === 'android') { // this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); }*/ } }) } componentWillUnmount() { this.mounted = false; this.blurListener.remove(); this.focusListener.remove() if (this.watchID) Geolocation.clearWatch(this.watchID); } backPressed = () => { Alert.alert( I18n.t('EXIT_TITLE'), I18n.t('EXIT_DESC'), [ {text: I18n.t('NO'), onPress: () => console.log('Cancel Pressed'), style: 'cancel'}, {text: I18n.t("YES"), onPress: () => BackHandler.exitApp()}, ], {cancelable: false}); return true; } constructor(props) { super(props, true); this.state = this.geInitialState(); this.mounted = false; this.filterOptions = [ {value: 5, label: "5 km"}, {value: 15, label: "15 km"}, {value: 20, label: "20 km"}, {value: 25, label: "25 km"} ]; Icon.getImageSource('md-car', 24, 'white').then((resutl) => { this.setState({caricon: resutl}) }); this._renderFavoriteIcon = this._renderFavoriteIcon.bind(this); this.makeMarkerInformation = this.makeMarkerInformation.bind(this); // IlinkEmitter.on("langueChange", this.updateLangue.bind(this)) }; updateLangue(){ this.props.navigation.setParams({name:I18n.t('MAP')}) let rand=Math.random() this.setState({lang:rand}) } makeCardSearch() { if(!this.state.isPubShow){ return ( this.openDrawer()} > Menu {this.state.filternetwork.name?this.state.filternetwork.name:this.state.network} {this.renderSupplementInformation()} {this.showLoadingMapView()} ) } } renderSupplementInformation(){ if(this.state.user && this.state.user.category==="geolocated"){ return () }else return ( {this.state.markers.length+" "+(this.state.currentNetworkSize===0?"":"/"+this.state.currentNetworkSize)} { this.setState({page:this.state.page + 1}) this.onLoadMore() }} style={{ borderRadius: 12, height: 32, width: 32, backgroundColor: "white", borderColor: "transparent", }}> =this.state.currentNetworkSize?"close":"refresh"} size={32} color={this.state.markers.length >=this.state.currentNetworkSize?"red":"grey"} /> ) } _renderMarker2(){ let {currentMarker, myPosition} = this.state; let marker=currentMarker const ma = {latitude: parseFloat(currentMarker.latitude), longitude: parseFloat(currentMarker.longitude)} const meter_distance = geolib.getDistance(myPosition, ma); const distanceTxt = (meter_distance > 900 ? (meter_distance / 1000) + " Km" : meter_distance + "m") + I18n.t('TO_YOU') var name = marker.lastname === null ? marker.adresse : marker.lastname return ( {name} { this.toggleSlidingUp(false) } }> {marker.adresse} {marker.network} {I18n.t('SOLDE_UNVAIBLE')} {distanceTxt} {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()} ) } _renderItemMarkerdetails(markers) { let marker = markers if (marker !== undefined && marker !== null) { let {currentMarker, myPosition} = this.state; const ma = {latitude: parseFloat(currentMarker.latitude), longitude: parseFloat(currentMarker.longitude)} const meter_distance = geolib.getDistance(myPosition, ma); const distanceTxt = (meter_distance > 900 ? (meter_distance / 1000) + " Km" : meter_distance + "m") + I18n.t('TO_YOU') var name = marker.lastname === null ? marker.adresse : marker.lastname return ( {name} { this.toggleSlidingUp(false) } }> {marker.adresse} {marker.network} {I18n.t('SOLDE_UNVAIBLE')} {distanceTxt} {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()} ); } } renderCurrentMarker(marker){ if(marker){ return( {name} { this.toggleSlidingUp(false) } }> {marker.adresse} {marker.network} {I18n.t('SOLDE_UNVAIBLE')} {distanceTxt} {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()} ) } } callItem(marker) { const args = { number: marker.phone, // String value with the number to call prompt: false // Optional boolean property. Determines if the user should be prompt prior to the call } call(args).catch((e)=>console.log(e)) } makeMarkerInformation() { let {currentMarker, myPosition} = this.state; // console.log(geolib.getDistance(myPosition,currentMarker)) if (currentMarker !== undefined && currentMarker !== null) { // this.setState({stateSheet:BottomSheetBehavior.STATE_EXPANDED}) return this._renderItemMarkerdetails(currentMarker); }else{ return (Impossible de'afficher l'element) } } makeActionButon() { let cu = this.state.user; if (cu) { switch (cu.category) { case "super": return this.getSuperActionButton(); break; case "geolocated": return this.geoLocatedAction(); break; case "hyper": return this.getHypervisorActionButton(); break; default: return this.getSimpleActionButton(); break; } } } getSuperActionButton() { return ( this.showMyMembers()} size={48} > this.refocusMap(false)} size={48} > { this.onMapTypeChange(); }} size={48} > ) } getSimpleActionButton() { return ( this.actionButton = r} > this.showFilterDialog()} size={48} > this.refocusMap(false)} size={48} > { this.onMapTypeChange(); } } size={48} > { this.showMynetworkMap(); }}> { this.showNewDialogNetwork(); }}> ) } toggleSlidingUp(state) { if(state && this.bottomSheetRef){ this.bottomSheetRef.snapTo(1) this.setState({showcurentMarker:state}) }else if(!state) this.bottomSheetRef.snapTo(0) const height = slideHeight let initialValue = !state ? 0:height , finalValue = !state ? height:0; this.setState({ panelVisible: state }); if (!state && this.state.needRoad) { this.setState({needRoad: false}); } this.state.animation.setValue(initialValue); //Step 3 Animated.timing( //Step 4 this.state.animation, { toValue: finalValue, duration:200, } ).start((animation)=>{ if(!state && this.map) { this.map.focusToUser() } }); } makeSlidingUp() { /*return ( this.onslidingEvent(event)} ref={(c) => this.panel = c} onRequestClose={() => this.setState({panelVisible: false, needRoad: false})}> {this.makeMarkerInformation()} )*/ return ( {this.bottomSheetRef=r}} snapPoints = {[0,"30%"]} renderHeader = {()=>this.markerView()} />) } _renderFavoriteIcon() { const {top, bottom} = this.props.draggableRange const draggedValue = this._draggedValue.interpolate({ inputRange: [bottom, top], outputRange: [1, 0], extrapolate: 'clamp' }) const transform = [{scale: draggedValue}] return ( { this.setState({needRoad: true}) }}> ) } geInitialState() { return { region: { latitude: 0, longitude: 0, latitudeDelta: 0.015, longitudeDelta: 0.0121, }, pas:100, prevRegion: { latitude: 0, longitude: 0, }, isPubShow:true, loadingDialog:true, textreach: "", currentNetworkSize:0, markersearchfilter: [], animation: new Animated.Value(0), myPosition: null, currentMarker: null, filterNetworkOption: radioOptions[1], needRoad: false, initialAnim: false, filternetwork: {}, destinationPosition: {}, panelVisible: false, markers: [], isNeedLoadMore: false, isLoadingMap: false, value: 5, page: 0, valuePosition: 0, markerfilter: null, allpoint: [], typeMap: 'standard', indexTypeMap: 0, user: null, snack_visible: false, snack_text_message: "", networks: [], dialogSliderVisible: false, showProgress: false, myNetwork: {}, dialogNetworkVisible: false, }; }; onMarkerPress(marker) { console.warn(marker) this.setState({currentMarker: marker}); this.toggleSlidingUp(true) } onMapTypeChange() { var newState = {index: this.state.indexTypeMap, text: this.state.typeMap}; newState.index = newState.index + 1; newState.index = newState.index % 3; switch (newState.index) { default: newState.text = 'standard'; break; case 1: newState.text = 'hybrid'; break; case 2: newState.text="terrain"; break; } this.setState({indexTypeMap: newState.index, typeMap: newState.text}); } /* { this.map=re if(re!=null) { this.mapRef = re.getMapRef(); } }} typeMap={this.state.typeMap} onMarkerClick={(e)=>this.onMarkerPress(e)} network={this.state.filternetwork} initialRegion={this.state.region} markers={this.state.markers} selectedMarker={this.state.currentMarker} myNetwork={this.state.myNetwork} lang={this.state.lang} myPosition={this.state.myPosition} onMapReady={()=>{ readUser().then((user) => { if (user) { this.setState({user: user}) this.setState({network: user.network}); if (Platform.OS === 'android') { this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); } } }) }} needRoad={this.state.needRoad} onNeedRoadReady={(data)=>{ this.setState({showProgress: false}) }} onNeedRoadError={(message)=>{ this.setState({showProgress: false}) Alert.alert(I18n.t("PROBLEM_OCCUR"),I18n.t("PROBLEM_OCCUR_DIRECTION"),[{text:"Ok",onPress:()=>{}}]) }} />*/ showInterticiel(){ if(this.state.isPubShow){ return ( this.setState({isPubShow:false})} navigation={this.props.navigation} />) } } renderBottomHome(){ return ( { this.map=re if(re!=null) { this.mapRef = re.getMapRef(); } }} typeMap={this.state.typeMap} onMarkerClick={(e)=>this.onMarkerPress(e)} network={this.state.filternetwork} initialRegion={this.state.region} markers={this.state.markers} selectedMarker={this.state.currentMarker} myNetwork={this.state.myNetwork} lang={this.state.lang} myPosition={this.state.myPosition} onMapReady={()=>{ readUser().then((user) => { if (user) { this.setState({user: user}) this.setState({network: user.network}); if(user.category){ this.setState({loadingDialog:false}) if (user.category !== "geolocated") { this.showMyMembers(); } else { if (myPosition.latitude <= 0 && myPosition.longitude <= 0) { this.props.navigation.push(route.updateinfo); } } }else{ if (Platform.OS === 'android') { this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); } } } }) }} needRoad={this.state.needRoad} onNeedRoadReady={(data)=>{ this.setState({showProgress: false}) }} onNeedRoadError={(message)=>{ this.setState({showProgress: false}) Alert.alert(I18n.t("PROBLEM_OCCUR"),I18n.t("PROBLEM_OCCUR_DIRECTION"),[{text:"Ok",onPress:()=>{}}]) }} /> {this.makeCardSearch()} {this.bottomSheetRef=r}} snapPoints = {[60,"30%","100%"]} renderHeader = {()=>this.renderHeader()} /> ) } renderInner(){ return ( Freud junior ) } markerView(){ if(this.state.currentMarker)return this._renderMarker2() } renderHeader(){ return ( { return ( ) }} style={{marginTop:40,marginRight:20}} buttonColor={theme.primary}/> {this.markerView()} {this.renderFilterMarker()} { if(!this.state.showFilterDistance){ this.bottomSheetRef.snapTo(2) this.setState({showFilterDistance:true}) }else{ this.bottomSheetRef.snapTo(0) this.setState({showFilterDistance:false}) } } }/> { this.bottomSheetRef.snapTo(2) this.setState({showdialogNetworkVisible:true}) }} /> {this.makeMarkerButton()} ) } renderFilterMarker(){ if(this.state.showFilterDistance) return ( {I18n.t('TEXT_FILTER_DISTANCE')} this.slidingComplete(item)} /> {(this.state.value === undefined ? 0 : this.state.value)} km {I18n.t("DISTANCE_ARROUND")} )} else return ( ) } renderOldHome(){ return ( {this.state.loadingDialog? {I18n.t("LOADING_DOTS")} :null } { this.map=re if(re!=null) { this.mapRef = re.getMapRef(); } }} typeMap={this.state.typeMap} onMarkerClick={(e)=>this.onMarkerPress(e)} network={this.state.filternetwork} initialRegion={this.state.region} markers={this.state.markers} selectedMarker={this.state.currentMarker} myNetwork={this.state.myNetwork} lang={this.state.lang} myPosition={this.state.myPosition} onMapReady={()=>{ readUser().then((user) => { if (user) { this.setState({user: user}) this.setState({network: user.network}); if(user.category){ this.setState({loadingDialog:false}) if (user.category !== "geolocated") { this.showMyMembers(); } else { if (myPosition.latitude <= 0 && myPosition.longitude <= 0) { this.props.navigation.push(route.updateinfo); } } }else{ if (Platform.OS === 'android') { this.requestCameraPermission(); } else { this.getPosition(); this.watchLocation(); }} } }) }} needRoad={this.state.needRoad} onNeedRoadReady={(data)=>{ this.setState({showProgress: false}) }} onNeedRoadError={(message)=>{ this.setState({showProgress: false}) Alert.alert(I18n.t("PROBLEM_OCCUR"),I18n.t("PROBLEM_OCCUR_DIRECTION"),[{text:"Ok",onPress:()=>{}}]) }} /> {this.makeCardSearch()} {this.makeSlidingUp()} {this.makeDialogLoader()} {this.makeDistanceDialog()} {this.makeNetworkChangeDialog()} {this.makeActionButon()} ) } renderTutoOldHome(){ return ( {this.makeCardSearch()} ) } render() { if(false){ return this.renderBottomHome() }else return this.renderOldHome() } renderCurrentMarker(){ if(this.state.currentMarker){ return ( {this.makeMarkerInformation()} ) } } makeDialogLoader() { return ( ) } showMynetworkMap(usr = null) { const user = usr === null ? this.state.user : usr let {myNetwork} =this.state; this.setState({filternetwork:myNetwork,page:0,filternetworkTemp:myNetwork,loadingDialog:true}) return new Promise(()=>{ if (myNetwork !== undefined) { this.loadingMarkers(this.state.myPosition,myNetwork,this.state.value).then((data) => { let items = data ? data : [] this.setState({loadingDialog:false}) if (user.category !== undefined && user.category !== null) { const filter = items.filter(item => item.code_parrain === user.code_membre) this.treatNewData(this.state.myPosition,filter,true) } else this.treatNewData(this.state.myPosition,items,true) }).catch((e) => { this.setState({loadingDialog:false}) console.log("error j") console.log(e) }) } else{ this.setState({loadingDialog:false}) console.log("error no net") } }) } showMyMembers() { let {code_membre} = this.state.user; if (code_membre !== undefined) { loadGroupeAgent(code_membre).then((data) => { if (data.success === 1) return this.setState({markers: data.datas}) }) } else console.log("error") } slidingComplete(itemSelected) { this.setState({value: this.filterOptions[itemSelected].value, valuePosition: itemSelected}); } makeDistanceDialog() { return ( { this.setState({dialogSliderVisible: false, showProgress: true}) setTimeout(() => this.filterPoint(), 300) } } cancelLabel={I18n.t("QUIT_")} okLabel={I18n.t('FILTER')} onCancel={()=> { this.setState({dialogSliderVisible: false}) }} onTouchOutside={() => this.setState({dialogSliderVisible: false})}> {I18n.t('TEXT_FILTER_DISTANCE')} this.slidingComplete(item)} /> {(this.state.value === undefined ? 0 : this.state.value)} km {I18n.t("DISTANCE_ARROUND")} ) } showFilterDialog() { this.setState({dialogSliderVisible: true}) } async filterPoint(){ const {value, myPosition, user, filternetwork} = this.state if (value !== undefined) { this.setState({page:0}) const metervalue = value * 1000 let res = this.state.networks.filter(function (item) { return item.id === filternetwork.id }) let reseau = res[0]; this.loadingMarkers(myPosition,filternetwork,value).then((datas)=>{ this.treatNewData(this.state.prevRegion,datas,true) }).catch((e)=>{ this.setState({showProgress: false}) Alert.alert(I18n.t("ERROR_FILTER"),I18n.t("ERROR_FILTER_TEXT"),[{text:I18n.t("CANCEL")},{text:I18n.t("RESTART"),onPress:()=>{this.filterPoint()}}]) }) } else { this.setState({showProgress: false}) this.setState({ snack_visible: true, snack_text_message: "impossible de filtrer les élements" }) setTimeout(() => { this.setState({snack_visible: false}) }, 5000) } } userChangeMarker(item) { const marker = this.state.markers[item]; if (this.mapRef !== null && this.mapRef !== undefined) { const reg = { latitude: parseFloat(marker.latitude), longitude: parseFloat(marker.longitude), latitudeDelta: 0.03, longitudeDelta: 0.01, } this.mapRef.animateToCoordinate({ latitude: parseFloat(marker.latitude), longitude: parseFloat(marker.longitude) }, 1000) this.mapRef.animateToRegion(reg, 1000) console.log(marker); } } geoLocatedAction() { return ( this.refocusMap()} size={48} > { this.onMapTypeChange(); } } size={48} > ) } makeNetworkChangeDialog() { return ( this.setState({dialogNetworkVisible: false})} onOk={result => { this.setState({dialogNetworkVisible: false,page:0}); this.setState({showProgress: true,filternetwork:this.state.filternetworkTemp}) setTimeout(()=>this.showFilterNetwork() ,500) }} > this.renderRow(item)}/> ) } renderRow = (row) => ( this.onRowPress(row)}> {row.name} ); onRowPress(rowID) { this.setState({filternetworkTemp: rowID}) } showNewDialogNetwork() { this.setState({dialogNetworkVisible: true}) } async showFilterNetwork() { const {myPosition, user, filternetwork} = this.state if (filternetwork !== undefined) { this.setState({showProgress: true}) this.loadingMarkers(this.state.myPosition,filternetwork,this.state.value,0).then((data) => { this.setState({showProgress: false}) this.treatNewData(myPosition,data,true) }).catch((e) => { this.setState({ snack_visible: true, snack_text_message: "Probleme de connexion" }) console.log(e) }) } else console.log("error no net") } showBtnItineraire() { return ( ) } showBtnClose() { return ( ) } markerManager:MarkerManager getHypervisorActionButton() { return ( this.refocusMap(false)} size={48} > { this.onMapTypeChange(); } } size={48} > ) } moveToMarker(item) { this.mapRef.animateToCoordinate({ latitude: parseFloat(item.latitude), longitude: parseFloat(item.longitude) }, 1000) this.setState({textreach: item.lastname, texta: true}) this.setState({markersearchfilter: []}); this.onMarkerPress(item) } refocusMap(zoom=true) { if(zoom){ if (this.mapRef && this.state.myPosition!==undefined) { this.mapRef.animateCamera({ center: { latitude: this.state.myPosition.latitude, longitude: this.state.myPosition.longitude }, pitch: 0, heading: 0, }, 1000) } }else{ if (this.mapRef && this.state.myPosition!==undefined) { this.mapRef.animateCamera({ center: { latitude: this.state.myPosition.latitude, longitude: this.state.myPosition.longitude }, pitch: 0, heading: 0, altitude: 5, zoom: 12 }, 1000) } } if(this.map) this.map.focusToUser() } renderCardSeashItem(item) { return ( { this.moveToMarker(item) }}> {item.firstname === null ? item.adresse : item.firstname} {item.lastname} {item.network} ) } retrieveAllPoint(dial_code) { /* let markers= this.markerManager.getLocalMarkers() console.log( markers.length) if(markers.length>0){ console.debug("load from local") for (let p of markers) { console.log(` ${p.lastname}`); } this.markerManager.close(); this.setState({allpoint: [], loadingDialog: false}) }else*/ getMakersFrom(dial_code).then((data) => { new Promise((resolve, reject) => { try { const ds =data.datas this.setState({allpoint: ds, loadingDialog: false}) resolve(ds) }catch (e) { //Crashlytics.log(e.message) console.warn(e.message) reject(new Error(e.message)) } }).then((ds)=>{ // this.markerManager.insertMarkers(ds).then((res)=>{console.warn(res)}) this.onLoadMore() }).catch((e)=>{ this.setState({loadingDialog:false}) //Crashlytics.log(e.message) console.log("on get marker") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.setState({loadingDialog:true}) if(dial_code!==null && dial_code!==undefined) this.retrieveAllPoint(dial_code) else this.requestCameraPermission() }} ], {cancelable:false} ) }) }).catch((e) => { console.log("on retreive>getmarkers",e.message) this.setState({loadingDialog:false}) if(this.state.allpoint.length<=0){ console.log("no point") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ if(this.state.allpoint.length<=0){ this.setState({loadingDialog:true}) if(dial_code!==null && dial_code!==undefined) this.retrieveAllPoint(dial_code) else this.requestCameraPermission() }} } ], {cancelable:false} ) } }) } showLoadMoreView() { if(this.state.isNeedLoadMore) return ( {(this.state.markers.length===0?this.state.markers.length:(this.state.markers.length))} / {this.state.currentNetworkSize} ) } showLoadingMapView() { if(this.state.isLoadingMap) return ( {I18n.t("LOADING_TEXT_MARKERS")+" "+this.state.value+" km "+I18n.t("DISTANCE_ARROUND")} ) } loadingMarkers(myPosition, filternetwork, value,p=undefined) { return new Promise((resolve,reject)=>{ const {allpoint}=this.state let page=p!==undefined?p:this.state.page let data=allpoint .filter((mark, index)=>{ const location={longitude:parseFloat(mark.longitude),latitude:parseFloat(mark.latitude)} return geolib.getDistance(myPosition,location)<=(value*1000) && mark.network===filternetwork.name}) .slice(0,(page+1)*this.state.pas) try{ const currentNetwork=allpoint .filter((mark, index)=>{ const location={longitude:parseFloat(mark.longitude),latitude:parseFloat(mark.latitude)} return geolib.getDistance(myPosition,location)<=(value*1000) && mark.network===filternetwork.name}) this.setState({currentNetworkSize:currentNetwork.length,currentNetworkMarkers:currentNetwork}) }catch(e){ console.debug("after "+e.message) } console.debug("data:",data,"value"+value*1000) resolve(data) }) } treatNewData(pos,data, isFilter = false) { this.setState({isLoadingMap: false}) let items = data; if (data.length > 0) { let corrent = items; if(isFilter) this.setState({showProgress: false}) if (corrent.length > 0) { this.setState({markers: corrent, prevRegion: pos}); } if (items.length { this.setState({snack_visible: false}) }, 5000) } this.setState({isNeedLoadMore: false}) } }else if(isFilter){ this.setState({markers:data} ); this.setState({ snack_visible: true, snack_text_message: I18n.t('NO_NETWORK_CORRESPONDING') }) setTimeout(() => { this.setState({snack_visible: false}) }, 5000) }else{ this.setState({markers: data}); } } async treatPosition(myPosition) { const myLastPosition = this.state.myPosition; console.log("on treatposition") if (myPosition.longitude!== myLastPosition.longitude||myPosition.latitude!== myLastPosition.latitude) { this.setState({myPosition:myPosition}) if(this.map)this.map.focusToUser() getPositionInformation(myPosition).then((response) => { if(response){ if (response.results !== undefined) { if (response.results.length > 0) { let most = response.results[0] let {address_components, formatted_address, place_id} = most this.setState({address: address_components, textadress: formatted_address, place: place_id}) let results = response.results; let shortcountry; let mcountry; for (let i = 0; i < results[0].address_components.length; i++) { for (let j = 0; j < results[0].address_components[i].types.length; j++) { if (results[0].address_components[i].types[j] === "country") { mcountry = results[0].address_components[i]; shortcountry = mcountry.short_name; this.setState({ shortCountry: mcountry.short_name, longCountry: mcountry.long_name }) } } } console.warn("there ") for (let i of countries) { if (i.code === shortcountry) { this.setState({indicatif: i.dial_code}) this.getNetworks(i.dial_code) } } } }else{ console.log("on treat 1") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.treatPosition(myPosition) }} ], {cancelable:false} ) } }else { console.log("on treat 2") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.treatPosition(myPosition) }} ], {cancelable:false} ) } }).catch((error)=>{ //Crashlytics.log(error.message) console.log("on treat 3") Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{ this.treatPosition(myPosition) }} ], {cancelable:false} ) }); const reg = { latitude: myPosition.latitude, longitude: myPosition.longitude, latitudeDelta: 0.03, longitudeDelta: 0.01, } this.setState({myPosition: myPosition, region: reg}); if(this.mapRef && !this.state.myPositionIsAnimated) { this.mapRef.animateCamera({ center: myPosition, pitch: 0, heading: 0, altitude: 5, zoom: 13 }, 1000) this.setState({myPositionIsAnimated:true}) } } } } export default Home; const markerDetails=StyleSheet.create({ solde:{ backgroundColor:theme.accent, color:"white", marginLeft:10, padding:5, fontSize:9, borderRadius:100, }, title:{ color:'black', marginLeft: 10, flex:1, fontSize:11, fontWeight: 'bold', }, subtitle2:{ color:'black', marginLeft: 10, flex:1, fontSize:10, fontWeight: 'bold', }, subtitle:{ color:'black', marginLeft: 9, fontSize:9 }, otherInformation:{ marginLeft:13, fontSize:9 }, reseau:{ marginLeft:10, fontWeight: 'bold', color:theme.accent, fontSize:10 }, container:{ flex:1, width:responsiveWidth(95), alignSelf:"center", paddingTop:responsiveHeight(1), marginBottom:responsiveHeight(1), backgroundColor:"white", justifyContent:'flex-start' } }) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#FFF', }, panelContainer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, }, panel: { height: 600, padding: 20, backgroundColor: '#f7f5eee8', }, header: { backgroundColor: '#f7f5eee8', shadowColor: '#000000', paddingTop: 20, borderTopLeftRadius: 20, borderTopRightRadius: 20, }, panelHandle: { width: 40, height: 8, borderRadius: 4, backgroundColor: '#00000040', marginBottom: 10, }, panelTitle: { fontSize: 27, height: 35, }, panelSubtitle: { fontSize: 14, color: 'gray', height: 30, marginBottom: 10, }, panelButton: { padding: 20, borderRadius: 10, backgroundColor: '#318bfb', alignItems: 'center', marginVertical: 10, }, panelButtonTitle: { fontSize: 17, fontWeight: 'bold', color: 'white', }, fab: { position: 'absolute', margin: 16, right: 0, bottom: 0, }, networkname:{ backgroundColor:theme.primary, padding:5, color:"white", marginRight:10, fontSize:10, borderRadius:12, }, myClusterTextStyle:{ color:"white" }, myClusterStyle: { backgroundColor:theme.accent, height:32, justifyContent:'center', alignItems:'center', width:32, borderRadius:16 }, rowContainer: { height: 52, flex: 1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', }, iconContainer: { marginRight: 16, }, mapmarker:{ width:52, height:52, }, slidingup:{ backgroundColor:"transparent", position:"absolute", height:slideHeight, bottom:0, left:responsiveWidth(2.5), width:responsiveWidth(95), zIndex: 1 }, panelHeader: { height: 120, backgroundColor: '#b197fc', alignItems: 'center', justifyContent: 'center' }, favoriteIcon: { left: responsiveWidth(75), backgroundColor: theme.primary, width: 64, justifyContent:'center', alignContent: 'center', bottom:-64, position:'absolute', height: 64, padding: 8, zIndex:1, borderRadius: 32, }, hambuger:{ color:theme.primary, borderColor:theme.primary, borderWidth:1, alignSelf:'center', padding:5, }, topBar:{ position:'absolute', alignSelf: 'center', justifyContent:'center', borderRadius:10, alignItems: 'center', marginTop:responsiveHeight(4), width:responsiveWidth(90), }, searchInput:{ flex:1, fontSize:14 }, search: { width:responsiveWidth(70), height:responsiveHeight(10), backgroundColor:'#00000000', }, map:{ width:responsiveWidth(100), height:responsiveHeight(100), }, backgroundd_drawer:{ backgroundColor:'#000', }, cardsearch:{ width:responsiveWidth(90), height:responsiveHeight(10), position:'absolute', alignSelf: 'center', marginTop: 5, }, actionButtonIcon: { fontSize: 20, height: 22, color: 'white', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });