@expo/vector-icons#MaterialIcons JavaScript Examples
The following examples show how to use
@expo/vector-icons#MaterialIcons.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: styles.js From atendimento-e-agilidade-medica-AAMed with MIT License | 5 votes |
MgGlass = styled(MaterialIcons)`
position: absolute;
top: 10px;
left: 20px;
color: #006bad;
font-size: 30px;
z-index: 10;
`
Example #2
Source File: CalendarHeader.js From ovuli with MIT License | 5 votes |
CalendarHeader = props => {
function onPressArrowLeft() {
props.onPressArrowLeft(props.month, props.addMonth);
}
function onPressArrowRight() {
props.onPressArrowRight(props.month, props.addMonth);
}
const month = moment(props.month.getTime())
.format('MMMM')
.toString();
const year = moment(props.month.getTime()).format('YYYY');
return (
<View>
<View style={styles.header}>
<TouchableOpacity onPress={onPressArrowLeft}>
<MaterialIcons name="keyboard-arrow-left" size={32} color="grey" />
</TouchableOpacity>
<Text style={styles.monthText}>
{month}
<Text style={styles.yearText}>{year}</Text>
</Text>
<TouchableOpacity style={styles.iconContainer} onPress={onPressArrowRight}>
<MaterialIcons name="keyboard-arrow-right" size={32} color="grey" />
</TouchableOpacity>
</View>
<View style={styles.week}>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={['#f54c63', '#f65e63', '#f78161']}
style={styles.linearGradient}
>
<View style={styles.weekDaysNamesStyle}>
{weekDaysNames.map((day, index) => (
<Text key={index} style={styles.weekName} numberOfLines={1}>
{day}
</Text>
))}
</View>
</LinearGradient>
</View>
</View>
);
}
Example #3
Source File: FocusedIcon.js From discovery-mobile-ui with MIT License | 5 votes |
FocusedIcon = ({
subType,
resourceIds,
isAccordion,
updateFocusedResources,
markedResources,
collectionId,
}) => {
const { marked } = markedResources;
const markedOrFocusedCount = resourceIds.reduce((acc, id) => (marked[id] ? acc + 1 : acc), 0);
const focusedCount = resourceIds.reduce((acc, id) => (marked[id] === FOCUSED ? acc + 1 : acc), 0);
const markedCount = resourceIds.reduce((acc, id) => (marked[id] === MARKED ? acc + 1 : acc), 0);
const allAreFocused = resourceIds.length === focusedCount;
const fullyFocused = focusedCount && (markedCount === 0);
const handlePress = () => {
if (isAccordion) { // could be one or more resourceId:
const newSubType = allAreFocused ? '' : subType; // no subType if turning all off
const resourceIdsMap = resourceIds.reduce((acc, id) => ({
...acc,
// eslint-disable-next-line max-len, no-nested-ternary
[id]: (marked[id] && fullyFocused) ? MARKED : (marked[id] === MARKED ? FOCUSED : marked[id]),
}), {});
updateFocusedResources(newSubType, resourceIdsMap, collectionId);
} else {
// (unmarked or marked) > focused > marked
updateFocusedResources(
subType,
{ [resourceIds[0]]: (focusedCount ? MARKED : FOCUSED) },
collectionId,
);
}
};
// eslint-disable-next-line no-nested-ternary, max-len
const iconColor = (fullyFocused ? Colors.fullyFocused : (focusedCount ? Colors.hasFocused : (markedOrFocusedCount) ? Colors.hasMarked : 'white'));
return (
<TouchableOpacity
{...{ onPress: (iconColor === 'white' ? undefined : handlePress) }}
>
<MaterialIcons name="center-focus-strong" size={24} color={iconColor} />
</TouchableOpacity>
);
}
Example #4
Source File: Main.js From SemanaOmnistack10 with MIT License | 4 votes |
function Main({ navigation }) {
const [devs, setDevs] = useState([]);
const [techs, setTechs] = useState('');
const [searching, setSearching] = useState(false);
const [currentRegion, setCurrentRegion] = useState(null);
const [keyboardShown, setKeyboardShown] = useState(false);
useEffect(() => {
async function loadInitialPosition() {
const { granted } = await requestPermissionsAsync();
if (granted) {
const { coords } = await getCurrentPositionAsync({
enableHighAccuracy: true
});
const { latitude, longitude } = coords;
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.04
});
}
}
loadInitialPosition();
Keyboard.addListener('keyboardDidShow', () => setKeyboardShown(true));
Keyboard.addListener('keyboardDidHide', () => setKeyboardShown(false));
}, []);
useEffect(() => {
subscribeToNewDevs(dev => setDevs([...devs, dev]));
}, [devs]);
function setupWebsocket() {
disconnect();
const { latitude, longitude } = currentRegion;
connect(
latitude,
longitude,
techs
);
}
async function loadDevs() {
if (searching)
return;
setSearching(true);
const { latitude, longitude } = currentRegion;
const response = await api.get('/search', { params: { latitude, longitude, techs } });
setDevs(response.data.devs);
setSearching(false);
setupWebsocket();
}
function handleRegionChange(region) {
setCurrentRegion(region);
}
if (!currentRegion)
return null;
return (
<>
<MapView
onRegionChangeComplete={handleRegionChange}
initialRegion={currentRegion}
style={styles.map}
>
{devs.map(dev => (
<Marker
key={dev._id}
coordinate={{
longitude: dev.location.coordinates[0],
latitude: dev.location.coordinates[1]
}}>
<Image style={styles.avatar} source={{ uri: dev.avatar_url }}></Image>
<Callout onPress={() => {
// Navegação
navigation.navigate('Profile', { github: dev.github });
}}>
<View style={styles.callout}>
<Text style={styles.devName}>{dev.name}</Text>
<Text style={styles.devBio}>{dev.bio}</Text>
<Text style={styles.devTechs}>{dev.techs.join(', ')}</Text>
</View>
</Callout>
</Marker>
))}
</MapView>
<View style={[styles.searchForm, (keyboardShown ? styles.searchTop : styles.searchBottom)]}>
<TextInput
style={styles.searchInput}
placeholder='Buscar devs por techs...'
placeholderTextColor='#999'
autoCapitalize='words'
autoCorrect={false}
value={techs}
onChangeText={setTechs}
/>
<TouchableOpacity onPress={loadDevs} disabled={searching} style={styles.searchButton}>
{!searching && <MaterialIcons name="my-location" size={20} color="#FFF" />}
{searching && <MaterialIcons name="gps-not-fixed" size={20} color="#FFF" />}
</TouchableOpacity>
</View>
</>
);
}
Example #5
Source File: index.js From atendimento-e-agilidade-medica-AAMed with MIT License | 4 votes |
export default function Home() {
const navigation = useNavigation();
const [hospitals, setHospitals] = useState([]);
const [user, setUser] = useState(null || '');
const [currentRegion, setCurrentRegion] = useState(null);
const [regionChange, setRegionChange] = useState(null);
const [currentLocation, setCurrentLocation] = useState(null);
const [description, setDescription] = useState('');
const [connection, setConnection] = useState(null);
const [isActiveButton, setIsActiveButton] = useState(false);
const [modal, setModal] = useState(false);
const [approved, setApproved] = useState(false);
const [hospitalName, setHospitalName] = useState('');
const [hospitalDest, setHospitalDest] = useState({});
const [distance, setDistance] = useState('');
const [duration, setDuration] = useState('');
const [userOrigin, setUserOrigin] = useState({ latitude: 0, longitude: 0 });
const [destination, setDestination] = useState({ latitude: 0, longitude: 0 });
// let conn;
useEffect(() => {
const conn = io('http://10.0.0.53:3333', {
query: { user_id: user._id },
});
setConnection(conn);
conn.on('solicitation_response', data => {
setHospitalDest(data);
setHospitalName(data.hospital.name);
data.approved ? setApproved(true) : setApproved(false);
setDestination({
latitude: data.hospital.location.coordinates[1],
longitude: data.hospital.location.coordinates[0],
});
});
conn.on('arrived__manually_mobile', data => {
const { arrived_mobile } = data;
if (arrived_mobile) {
setDuration('');
setDistance('');
setDestination({ latitude: 0, longitude: 0 });
setModal(false);
setApproved(false);
}
});
conn.on('warning', data => {
const { not_here } = data;
if (not_here) {
setDuration('');
setDistance('');
setDestination({ latitude: 0, longitude: 0 });
setModal(false);
setApproved(false);
Alert.alert(
'Você não compareceu',
'Você tem mais 2 oportunidades antes de ser banido'
);
}
});
}, []);
useEffect(() => {
function getUserLogged() {
return new Promise((resolve, result) => {
setTimeout(() => {
resolve(AsyncStorage.getItem('store'));
}, 1000);
});
}
getUserLogged()
.then(data => {
const dataParse = JSON.parse(data);
setUser(dataParse.auth.user);
})
.catch(error => console.log(error));
watchPositionAsync(
{
accuracy: Accuracy.High,
timeInterval: 10000,
enableHighAccuracy: true,
},
data => {
console.log('10s se passaram');
setUserOrigin({
latitude: data.coords.latitude,
longitude: data.coords.longitude,
});
if (approved) {
console.log('aprovado');
fetch(
'https://maps.googleapis.com/maps/api/geocode/json?address=' +
data.coords.latitude +
',' +
data.coords.longitude +
'&key=' +
GOOGLE_MAPS_APIKEY
)
.then(response => response.json())
.then(responseJson => {
setCurrentLocation(responseJson.results[0].formatted_address);
});
if (
calculateDistance(data.coords, destination) == 0.01 ||
calculateDistance(data.coords, destination) == 0.02
) {
console.log('chegou');
connection.emit('arrived', {
hospital_id: hospitalDest.hospital._id,
user,
arrived: true,
});
setApproved(false);
setDestination({ latitude: 0, longitude: 0 });
setModal(!modal);
setDuration(null);
setDistance(null);
}
}
}
);
}, []);
// função que vai carregar a posição inicial do paciente no mapa
useEffect(() => {
async function loadInitialPosition() {
const { granted } = await requestPermissionsAsync();
if (!granted) {
return Alert.alert('Ops', 'Você precisa habilitar a permissão');
}
const { coords } = await getCurrentPositionAsync({
enableHighAccuracy: true,
});
const { latitude, longitude } = coords;
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.014,
longitudeDelta: 0.014,
});
setUserOrigin({
latitude: latitude,
longitude: longitude,
});
fetch(
'https://maps.googleapis.com/maps/api/geocode/json?address=' +
latitude +
',' +
longitude +
'&key=' +
GOOGLE_MAPS_APIKEY
)
.then(response => response.json())
.then(responseJson => {
setCurrentLocation(responseJson.results[0].formatted_address);
});
}
loadInitialPosition();
//handlePositionUpdate();
}, [currentRegion]);
useEffect(() => {
async function loadHospitals() {
const { latitude, longitude } = currentRegion || 1;
if (latitude && longitude) {
try {
const response = await api.get('search', {
params: {
longitude,
latitude,
},
});
setHospitals(response.data.hospitais);
} catch (err) {
console.debug('[ERROR: loadHospitals] => ', err);
}
}
}
loadHospitals();
}, [currentRegion]);
async function handleSolicitation() {
const hospital_ids = [];
hospitals.map(hospital => {
hospital_ids.push(hospital._id);
});
if (description === '') return Alert.alert('AVISO', 'Preencha o campo.');
connection.emit('user_solicitation', {
hospital_ids,
user,
description,
currentLocation,
});
Alert.alert(
'Solicitação enviada',
'Sua solicitação de atendimento foi enviada aos hospitais próximos à sua localização.'
);
Keyboard.dismiss();
setDescription('');
setIsActiveButton(true);
setModal(true);
setTimeout(() => {
setIsActiveButton(false);
}, 1000);
}
function rad(x) {
return (x * Math.PI) / 180;
}
function calculateDistance(pointA, pointB) {
let R = 6378137;
let dLat = rad(pointB.latitude - pointA.latitude);
let dLong = rad(pointB.longitude - pointA.longitude);
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(pointA.latitude)) *
Math.cos(rad(pointB.latitude)) *
Math.sin(dLong / 2) *
Math.sin(dLong / 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = (R * c) / 1000;
return d.toFixed(2);
}
async function handleRegionChanged(region) {
setRegionChange(region);
}
if (!currentRegion) {
return null;
}
return (
<View style={styles.container}>
<Header flag={true} navigation={navigation} />
<MapView
onRegionChangeComplete={handleRegionChanged}
initialRegion={currentRegion}
showsUserLocation
loadingEnabled={true}
style={styles.mapContainer}
>
{approved && !!destination.latitude && !!destination.longitude && (
<MapViewDirections
origin={userOrigin}
onReady={result => {
setDistance(result.distance);
setDuration(result.duration);
}}
onError={err => console.log(err)}
destination={destination}
apikey={GOOGLE_MAPS_APIKEY}
strokeWidth={4}
strokeColor={'#222'}
/>
)}
{hospitals.map(hospital => (
<Marker
key={hospital._id}
coordinate={{
latitude: hospital.location.coordinates[1],
longitude: hospital.location.coordinates[0],
}}
>
<MaterialCommunityIcons
name="hospital-marker"
size={40}
color="#0984e3"
/>
<Callout style={styles.calloutHospital}>
<Text style={styles.name}>{hospital.name}</Text>
<Text style={styles.desc}>
<Text style={styles.tittles}>RUA:</Text>{' '}
{hospital.address.street}
</Text>
<Text>
<Text style={styles.tittles}>BAIRRO:</Text>{' '}
{hospital.address.neighborhood}
</Text>
<Text>
<Text style={styles.tittles}>CEP:</Text> {hospital.address.cep}
</Text>
<Text>
<Text style={styles.tittles}>TELEFONE: </Text>
{hospital.phone}
</Text>
</Callout>
</Marker>
))}
</MapView>
{modal ? (
<Animatable.View
style={styles.modal}
animation="fadeInDown"
duration={1000}
useNativeDriver
>
{!approved ? (
<>
<FontAwesome name="circle" size={15} color="#ff9f1a" />
<Text>Solicitação aguardando aprovação do hospital.</Text>
</>
) : (
<>
<FontAwesome name="circle" size={15} color="#0ec445" />
<Text>
Sua solicitação foi aprovada em {hospitalName}.{'\n'}
Tempo estimado: {`${Math.round(duration)} min \n`}
Distância: {`${Number(distance).toFixed(2)} km`}
</Text>
</>
)}
</Animatable.View>
) : null}
{!approved && (
<View style={styles.searchForm}>
<TextInput
style={styles.searchInput}
placeholder="Descrição..."
placeholderTextColor="#999"
autoCapitalize="words"
autoCorrect={false}
multiline
value={description}
onChangeText={setDescription}
/>
<TouchableOpacity
onPress={handleSolicitation}
style={
isActiveButton
? [styles.loadButton, { backgroundColor: '#006bad55' }]
: styles.loadButton
}
disabled={isActiveButton}
>
<MaterialIcons name="send" size={25} color="#fff" />
</TouchableOpacity>
</View>
)}
<View style={styles.mapDrawerOverlay} />
</View>
);
}
Example #6
Source File: Main.js From devradar with MIT License | 4 votes |
function Main({ navigation }) {
const [devs, setDevs] = useState([])
const [currentRegion, setCurrentRegion] = useState(null)
const [techs, setTechs] = useState('')
useEffect(() => {
async function loadInitialPosition() {
const { granted } = await requestPermissionsAsync()
if (granted) {
const { coords } = await getCurrentPositionAsync({
enableHighAccuracy: true
})
const { latitude, longitude } = coords
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.04
})
}
}
loadInitialPosition()
}, [])
useEffect(() => {
subscribeToNewDevs(dev => {
setDevs([...devs, dev])
})
}, [devs])
function setupWebsocket() {
disconnect()
const { latitude, longitude } = currentRegion
connect(latitude, longitude, techs)
}
async function loadDevs() {
const { latitude, longitude } = currentRegion
const response = await api.get('/search', {
params: {
latitude,
longitude,
techs
}
})
setDevs(response.data)
setupWebsocket()
}
function handleRegionChange(region) {
setCurrentRegion(region)
}
if (!currentRegion) {
return null
}
return (
<>
<MapView onRegionChange={handleRegionChange} initialRegion={currentRegion} style={ styles.map }>
{ devs.map(dev => (
<Marker
key={dev._id}
coordinate={{
longitude: dev.location.coordinates[0],
latitude: dev.location.coordinates[1]
}}
>
<Image
style={styles.avatar}
source={{ uri: dev.avatar_url }}
/>
<Callout onPress={() => {
navigation.navigate('Profile', {
github_username: dev.github_username
})
}}>
<View style={styles.callout}>
<Text style={styles.devName}>{dev.name}</Text>
<Text style={styles.devBio}>{dev.bio}</Text>
<Text style={styles.devTechs}>{dev.techs.join(', ')}</Text>
</View>
</Callout>
</Marker>
))}
</MapView>
<View style={styles.searchForm}>
<TextInput
style={styles.searchInput}
placeholder="Buscar devs por techs..."
placeholderTextColor="#999"
autoCapitalize="words"
autoCorrect={false}
value={techs}
onChangeText={setTechs}
/>
<TouchableOpacity onPress={loadDevs} style={styles.loadButton}>
<MaterialIcons name="my-location" size={20} color='#FFF' />
</TouchableOpacity>
</View>
</>
)
}
Example #7
Source File: Main.js From OmniStack-10.0 with MIT License | 4 votes |
function Main({ navigation }) {
const [devs, setDevs] = useState([])
const [currentRegion, setCurrentRegion] = useState(null);
const [techs, setTechs] = useState('');
useEffect(() => {
async function loadInitialPosition() {
const { granted } = await requestPermissionsAsync();
if (granted) {
const { coords } = await getCurrentPositionAsync({
enableHighAccuracy: true,
});
const { latitude, longitude } = coords;
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.04,
})
}
async function newFunction() {
return await requestPermissionsAsync();
}
}
loadInitialPosition();
}, []);
useEffect(() => {
subscribeToNewDevs(dev => setDevs([...devs, dev]));
}, [devs])
function setupWebsocket() {
disconnect();
const{ latitude, longitude } = currentRegion;
connect(
latitude,
longitude,
techs,
);
}
async function loadDevs() {
const { latitude, longitude } = currentRegion;
console.log(currentRegion);
const response = await api.get('/search', {
params: {
latitude,
longitude,
techs
}
});
setDevs(response.data.devs);
setupWebsocket();
}
function handleRagionChanged(region) {
setCurrentRegion(region);
}
if (!currentRegion) {
return null;
}
return (
<>
<MapView onRegionChangeComplete={handleRagionChanged}
initialRegion={currentRegion}
style={styles.map}
>
{devs.map(dev => (
<Marker
key={dev._id}
coordinate={{
longitude: dev.location.coordinates[0],
latitude: dev.location.coordinates[1],
}}
>
<Image
style={styles.avatar}
source={{ uri: dev.avatar_url }}
/>
<Callout onPress={() => {
navigation.navigate('Profile', { github_username: dev.github_username });
}}>
<View style={styles.callout}/>
<Text style={styles.devName}>{dev.name}</Text>
<Text style={styles.devBio}>{dev.bio}</Text>
<Text style={styles.devTechs}>{dev.techs.join(', ')}</Text>
</Callout>
</Marker>
))}
</MapView>
<View style={styles.searchForm}>
<TextInput
style={styles.searchInput}
placeholder="Buscar devs por techs..."
placeholderTextColor="#999"
autoCapitalize="words"
autoCorrect={false}
value={techs}
onChangeText={setTechs}
/>
<TouchableOpacity onPress={loadDevs} style={styles.loadButton}>
<MaterialIcons name="my-location" size={20} color="#FFF" />
</TouchableOpacity>
</View>
</>
);
}
Example #8
Source File: Login.js From juken with MIT License | 4 votes |
Login = ({ startDemo }) => {
const [ token, setToken ] = useState('');
const failed = useRef(null);
const empty = useRef(null);
const { showActionSheetWithOptions } = useActionSheet();
const colorScheme = useColorScheme();
const login = useStoreActions(actions => actions.session.login);
const loginLoading = useStoreState(state => state.loadings.login);
return (
<>
<TouchableWithoutFeedback
onPress={() => {
if (device('mobile')) Keyboard.dismiss();
}}
>
<View style={[styles.page, colorScheme === 'light' ? null : styles.page_dark]}>
{/* toasts */}
<Toast ref={failed} type={TYPES.ERROR} />
<Toast ref={empty} type={TYPES.WARNING} />
{/* page */}
<Page style={[styles.page, colorScheme === 'light' ? null : styles.page_dark]}>
<KeyboardAvoidingView
style={styles.container}
behavior={device('ios') ? 'padding' : 'height'}
>
<View style={styles.imageWrapper}>
<Image source={require('./logo.png')} style={styles.imageIcon} />
<Image source={require('./wa2.png')} style={styles.imageText} />
</View>
<TextInput
placeholder="WaniKani Personal Access Token"
value={token}
onChangeText={text => setToken(text)}
/>
{/* login button */}
<Button
style={{ marginTop: 8 }}
textStyle={{ color: colorScheme === "light" ? theme.palette.black: theme.palette_dark.lightGray }}
text={loginLoading ? 'Logging in...' : 'Login'}
iconRight={
loginLoading
? <ActivityIndicator size={24} color={colorScheme === "light" ? theme.palette.black: theme.palette_dark.lightGray} />
: <AntDesign name="arrowright" size={24} color={theme.palette.black} />
}
disabled={loginLoading}
onPress={() => {
if (device('mobile')) Keyboard.dismiss();
if (!token) {
empty.current.show('Please enter your API token');
return;
}
if (token === '1111') {
startDemo();
return;
}
login({
token,
onFail: () => failed.current.show('Invalid token')
});
}}
/>
{/* more button */}
{device('mobile') && (
<Button
textStyle={{ color: theme.palette.white }}
text="More"
style={{ marginTop: 12, backgroundColor: 'transparent' }}
onPress={() => {
showActionSheetWithOptions({
options: [
'Cancel',
'Feedback',
'Report Issues',
'Source Code',
device('ios') ? null : 'Demo',
].filter(Boolean),
}, async buttonIndex => {
if (buttonIndex === 1) {
await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
} else if (buttonIndex === 2) {
await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
} else if (buttonIndex === 3) {
await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
} else if (buttonIndex === 4) {
startDemo()
}
})
}}
/>
)}
{/** do not show this part for iOS */}
{device('web') && (
<>
<View style={styles.or}>
<Text style={styles.orText}>-or-</Text>
</View>
{/* demo button */}
<Button
text="Demo"
iconLeft={<MaterialCommunityIcons name="test-tube" size={24} color={theme.palette.black} />}
onPress={() => startDemo()}
/>
{/* feedback button */}
<Button
style={{ marginTop: 8 }}
text="Feedback & Bug Report"
iconLeft={<MaterialIcons name="email" size={24} color={theme.palette.black} />}
onPress={async () => {
await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
}}
/>
{/* source code button */}
<Button
style={{
marginTop: 8,
backgroundColor: theme.color.githubBlack
}}
textStyle={{
color: theme.color.githubWhite
}}
text="Source Code"
iconLeft={<AntDesign name="github" size={24} color={theme.color.githubWhite} />}
onPress={async () => {
await WebBrowser.openBrowserAsync('https://github.com/oguzgelal/juken')
}}
/>
</>
)}
</KeyboardAvoidingView>
</Page>
</View>
</TouchableWithoutFeedback>
</>
)
}
Example #9
Source File: Main.js From FinDevs with MIT License | 4 votes |
function Main({navigation}){
const [devs, setDevs] = useState([])
const [currentRegion, setCurrentRegion] = useState(null)
const [techs, setTechs] = useState('')
useEffect(() => {
subscribeToNewDevs(dev => setDevs([...devs, dev]))
}, [devs])
useEffect(() => {
async function loadInitialPosition(){
const {granted} = await requestPermissionsAsync()
if (granted){
const {coords} = await getCurrentPositionAsync({
enableHighAccuracy: true
})
const {latitude, longitude} = coords;
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.05,
longitudeDelta: 0.05
})
}
}
loadInitialPosition()
}, [])
function setupWebSocket(){
disconnect()
const {latitude, longitude} = currentRegion;
connect(
latitude,
longitude,
techs
)
}
async function loadDevs(){
const {latitude, longitude } = currentRegion;
const response = await api.get('/search', {
params:{
latitude,
longitude,
techs,
}
})
setDevs(response.data)
setupWebSocket()
Keyboard.dismiss()
}
function handleRegionChanged(region){
setCurrentRegion(region)
}
if(!currentRegion){
return null
}
return (
<>
<MapView onRegionChangeComplete={handleRegionChanged}
initialRegion={currentRegion}
style={styles.map}>
{devs.map(dev => (
<Marker
key={dev._id}
coordinate={
{latitude: dev.location.coordinates[1],
longitude: dev.location.coordinates[0]
}}>
<Image
style={styles.avatar}
source={{
uri: dev.avatar_url
}}/>
<Callout onPress={() => {
navigation.navigate('Profile', {github_user: dev.github_user})
}}>
<View style={styles.callout}>
<Text style={styles.devName}>{dev.name}</Text>
<Text style={styles.devBio}>{dev.bio}</Text>
<Text style={styles.devTechs}>{dev.techs.join(', ')}</Text>
</View>
</Callout>
</Marker>
))}
</MapView>
<View style={styles.searchForm}>
<TextInput
style={styles.searchInput}
placeholder="Buscar Devs por Techs"
placeholderTextColor="#999"
autoCapitalize="words"
autoCorrect={false}
value={techs}
onChangeText={setTechs}
/>
<TouchableOpacity style={styles.loadButton} onPress={loadDevs}>
<MaterialIcons name="my-location" size={20} color="#FFF"/>
</TouchableOpacity>
</View>
</>
)
}
Example #10
Source File: Main.js From semana-omnistack-10 with MIT License | 4 votes |
function Main({ navigation }) {
const [devs, setDevs] = useState([]);
const [currentRegion, setCurrentRegion] = useState(null);
const [techs, setTechs] = useState('');
useEffect(() => {
async function loadInitialPosition() {
const { granted } = await requestPermissionsAsync();
if (granted) {
const { coords } = await getCurrentPositionAsync({
enableHighAccuracy: true,
});
const { latitude, longitude } = coords;
setCurrentRegion({
latitude,
longitude,
latitudeDelta: 0.04,
longitudeDelta: 0.04,
})
}
}
loadInitialPosition();
}, []);
useEffect(() => {
subscribeToNewDevs(dev => setDevs([...devs, dev]));
}, [devs]);
function setupWebsocket() {
disconnect();
const { latitude, longitude } = currentRegion;
connect(
latitude,
longitude,
techs,
);
}
async function loadDevs() {
const { latitude, longitude } = currentRegion;
const response = await api.get('/search', {
params: {
latitude,
longitude,
techs
}
});
setDevs(response.data.devs);
setupWebsocket();
}
function handleRegionChanged(region) {
setCurrentRegion(region);
}
if (!currentRegion) {
return null;
}
return (
<>
<MapView
onRegionChangeComplete={handleRegionChanged}
initialRegion={currentRegion}
style={styles.map}
>
{devs.map(dev => (
<Marker
key={dev._id}
coordinate={{
longitude: dev.location.coordinates[0],
latitude: dev.location.coordinates[1],
}}
>
<Image
style={styles.avatar}
source={{ uri: dev.avatar_url }}
/>
<Callout onPress={() => {
navigation.navigate('Profile', { github_username: dev.github_username });
}}>
<View style={styles.callout}>
<Text style={styles.devName}>{dev.name}</Text>
<Text style={styles.devBio}>{dev.bio}</Text>
<Text style={styles.devTechs}>{dev.techs.join(', ')}</Text>
</View>
</Callout>
</Marker>
))}
</MapView>
<View style={styles.searchForm}>
<TextInput
style={styles.searchInput}
placeholder="Buscar devs por techs..."
placeholderTextColor="#999"
autoCapitalize="words"
autoCorrect={false}
value={techs}
onChangeText={setTechs}
/>
<TouchableOpacity onPress={loadDevs} style={styles.loadButton}>
<MaterialIcons name="my-location" size={20} color="#FFF" />
</TouchableOpacity>
</View>
</>
);
}