react-native-maps#Marker JavaScript Examples

The following examples show how to use react-native-maps#Marker. 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: MapView.js    From Legacy with Mozilla Public License 2.0 6 votes vote down vote up
MapMarker = React.memo(function (props) {
  const [tracksViewChanges, setTracksViewChanges] = React.useState(true);
  return <Marker
    tracksViewChanges={tracksViewChanges}
    coordinate={{ latitude: props.lat, longitude: props.lng }}
  >
    <Image
      onLoad={()=>setTracksViewChanges(false)}
      fadeDuration={0}
      source={getIcon(props.icon)}
      style={{ width: 48, height: 48 }}/>
  </Marker>
})
Example #2
Source File: ClusterMarker.js    From guardioes-app with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <Marker
        anchor={{x: 0.5, y: 0.5}}
        centerOffset={{x: 0.5, y: 0.5}}
        coordinate={this.state.coordinate}
        image={this.state.image}
        title={translate('map.people') + this.state.pointCount}
        description={this.state.message}
        tracksViewChanges={true}
      />
    );
  }
Example #3
Source File: LocationScreen.js    From react-native-booking-app with MIT License 6 votes vote down vote up
render() {
        return (
            <SafeAreaView style={styles.container}>
                <MapView
                    style={{flex: 1,}}
                    initialRegion={{
                        latitude: 27.994402,
                        longitude: -81.760254,
                        latitudeDelta: 5,
                        longitudeDelta: 5,
                    }} >
                    {this.state.markers.map((marker, idx) => (
                        <Marker
                            key={idx}
                            coordinate={{
                                latitude: marker.lat,
                                longitude: marker.long,
                            }}
                            image={require('../../assets/images/marker.png')}
                            title={marker.title}
                            onCalloutPress={e => this.onDetail(idx)}
                        />
                    ))}
                </MapView>
            </SafeAreaView>
        )
    }
Example #4
Source File: MapMarker.js    From covid-19-app with MIT License 6 votes vote down vote up
MapMarker = ({ data }) => {
    return (
        <Marker
            coordinate={data.coordinates}
            tracksViewChanges={false}
            anchor={{ x: 0.5, y: -0.5 }}
        >
            <View style={styles.map.marker.container}>
                <Text style={styles.map.marker.title}>{numeral(data.cases.active).format('0,0')}</Text>
            </View>
        </Marker>
    )
}
Example #5
Source File: index.native.jsx    From polaris with Apache License 2.0 6 votes vote down vote up
MapView = () => {
  const [region, setRegion] = useState(startingRegion)
  const [markers, setMarkers] = useState([])
  useEffect(() => {
    const newMarkers = [...markers, ...generateMarkers(10, region)]
    if (newMarkers.length > 50) {
      newMarkers.splice(0, 10)
    }
    setMarkers(newMarkers)
  }, [region])

  return (
    <Container>
      <MapViewNative
        onRegionChangeComplete={r => setRegion(r)}
        style={{ width: '100%', height: '100%' }}
        initialRegion={startingRegion}
      >
        {markers.map(({ coords, name, description, id }) => {
          return (
            <Marker coordinate={coords} key={id}>
              <Callout>
                <Container>
                  <Title>{name}</Title>
                  <Description>{description}</Description>
                </Container>
              </Callout>
            </Marker>
          )
        })}
      </MapViewNative>
    </Container>
  )
}
Example #6
Source File: Map.js    From timetable with MIT License 5 votes vote down vote up
Map = ({ polylineSource, markerSource, onPressHandler, isDark }) => {
  // MapView Markers
  const markers = () => {
    if (markerSource.length > 0) {
      return markerSource.map((marker, index) => {
        const coords = {
          latitude: marker.Lat,
          longitude: marker.Lon
        }

        return (
          <Marker
            key={index}
            coordinate={coords}
            title={marker.Name}
            description={' '}
            onPress={() => onPressHandler(marker.StopId, marker.Name)}
            pinColor={'#de373d'}
            tracksViewChanges={false}
            icon={require('../assets/images/b.png')}
          />
        )
      })
    }
  }

  // MapView Polylines
  const polylines = () => {
    if (polylineSource != null) {
      return (
        <Polyline
          coordinates={polylineSource}
          strokeWidth={4}
          strokeColor='#fff829'
        />
      )
    }
  }

  return (
    <MapView
      style={{ flex: 1 }}
      provider='google'
      initialRegion={{
        latitude: 41.7330215,
        longitude: 44.7989883,
        latitudeDelta: 0.35,
        longitudeDelta: 0.25
      }}
      clusterColor={isDark ? 'rgba(255, 0, 0, 0.4)' : 'rgba(255, 0, 0, 0.5)'}
      radius={170}
      extent={700}
      showsCompass={true}
      customMapStyle={isDark ? night : day}
      showsUserLocation={true}
      showsMyLocationButton={true}
      followsUserLocation={true}
    >
      {markers()}

      {polylines()}
    </MapView>
  )
}
Example #7
Source File: MapDetail.js    From deprem with GNU Lesser General Public License v3.0 5 votes vote down vote up
function MapDetail({ route, navigation }) {
  searchGoogle = () => {
    Linking.openURL(`https://www.google.com/search?q=${route.params.item.title}`)
  }
  return (
    <View>
      <View style={styles.headerView}>
        <IconButton
          onPress={() => navigation.goBack()}
          name="arrow-left"
          style={styles.backIconButton}
          color={Colors.white}
        />

        <Text style={styles.titleText}>Deprem Haritası</Text>
        <Text style={styles.subtitleText}>{route.params.item.title}</Text>
        <View style={[styles.buttonView]}>
          <IconButton
            onPress={searchGoogle}
            name="map-search"
            color={Colors.success}
            size={40}
          />
        </View>
      </View>
      <View style={styles.contentView}>
        <MapView
          provider={PROVIDER_GOOGLE}
          style={styles.map}
          region={{
            latitude: route.params.item.lat,
            longitude: route.params.item.lng,
            latitudeDelta: 1,
            longitudeDelta: 1,
          }}
        >
          <Marker
            title={route.params.item.title}
            description={`Deprem Şiddeti: ${route.params.item.mag}`}
            coordinate={{
              latitude: route.params.item.lat,
              longitude: route.params.item.lng
            }}
          />
        </MapView>

      </View>
    </View>
  );
}
Example #8
Source File: Map.js    From deprem with GNU Lesser General Public License v3.0 5 votes vote down vote up
function MapDetail({ route, navigation }) {
  const [mapResult, setResult] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  fetchData = async (callback) => {
    await Axios.get('https://api.orhanaydogdu.com.tr/deprem/live.php?limit=100')
      .then(res => {
        setResult(res.data.result);

        if (typeof callback === 'function') {
          callback(res.data.result);
        }
      })
      .catch(err => alert(err));
  }

  return (
    <View>
      <View style={styles.headerView}>
        <Text style={styles.titleText}>Deprem</Text>
        <Text style={styles.subtitleText}>Güncel Deprem Haritası</Text>
        <View style={[styles.buttonView]}>
          <IconButton
            onPress={fetchData}
            name="refresh"
            color={Colors.success}
            size={40}
          />
        </View>
      </View>
      <View style={styles.contentView}>
        <MapView
          provider={PROVIDER_GOOGLE}
          style={styles.map}
          region={{
            latitude: 40,
            longitude: 36,
            latitudeDelta: 26,
            longitudeDelta: 26,
          }}
        >
          {
            mapResult.map((item, index) => {
              return (
                <Marker key={index}
                  onPress={() => navigation.navigate('QuakeDetail', { item: item })}
                  title={item.title}
                  description={`Deprem Şiddeti: ${item.mag}`}
                  coordinate={{
                    latitude: item.lat,
                    longitude: item.lng
                  }}
                >
                </Marker>
              );
            })
          }
        </MapView>
      </View>
    </View>
  );
}
Example #9
Source File: index.js    From pandoa with GNU General Public License v3.0 4 votes vote down vote up
MapHistory = ({ positions, setDetailTrigger, warnings }) => {
  const lines = positions.map(point => {
    return {
      latitude: point.lat ? point.lat : 0,
      longitude: point.lng ? point.lng : 0
    };
  });

  const connectedPoints = warnings;

  var concatPoints = [];
  connectedPoints.forEach((position, i) => {
    const foundSimilar = concatPoints.findIndex(existingPoint => {
      const diff = diffCalc(position, existingPoint);
      if (diff.distance <= 100 && diff.timeDifference <= 1000 * 60 * 60 * 2) {
        return true;
      }
    });
    if (foundSimilar === -1) {
      concatPoints.push(position);
    }
  });

  const circle = positions.map((point, index) => {
    const coordinates = {
      longitude: point.lng,
      latitude: point.lat
    };
    return (
      <Circle
        key={index}
        strokeColor={commonColor.brandPrimary}
        center={coordinates}
        fillColor={commonColor.brandPrimary}
        radius={Platform.OS === "ios" ? 0.3 : 0.1}
      />
    );
  });

  const connectedLines = connectedPoints.map((point, index) => {
    if (point.matches && point.matches.length >= 1) {
      return point.matches.map((e, i) => (
        <Polyline
          key={`${i}-${index}`}
          coordinates={[
            { latitude: point.position.lat, longitude: point.position.lng },
            { latitude: e.lat, longitude: e.lng }
          ]}
          strokeColor="rgba(255,0,0,0.1)" // fallback for when `strokeColors` is not supported by the map-provider
          strokeColors={["rgba(255,0,0,0.5)", "rgba(255,168,12,0.8)"]}
          strokeWidth={15.5}
        />
      ));
    }
  });

  const points = connectedPoints.map((point, index) => {
    const coordinates = {
      longitude: point.position.lng,
      latitude: point.position.lat
    };

    return (
      <Marker
        key={index}
        anchor={Platform.OS === "ios" ? { x: 0, y: 0 } : { x: 0.53, y: 0.53 }}
        coordinate={coordinates}
        onCalloutPress={() => setDetailTrigger(point)}
        title={`${new Date(point.position.time).toLocaleDateString(
          "de-DE",
          options
        )}`}
        description={contactLengthText(point.duration)}
      >
        {point.matches.length >= 1 ? (
          <View style={styles.matchCircle}>
            <View style={styles.matchCircleBackground}></View>
            <View style={styles.matchCircleInner}></View>
          </View>
        ) : (
          <View style={styles.historyCircle} />
        )}
      </Marker>
    );
  });

  //
  //
  //
  return (
    <React.Fragment>
      <Polyline
        coordinates={lines}
        geodesic={true}
        // strokeColor={Colors.tintColor}  fallback for when `strokeColors` is not supported by the map-provider
        strokeWidth={2}
        strokeColor="rgba(0,122,255,0.7)"
      />
      {circle}
      {connectedLines}
      {points}
    </React.Fragment>
  );
}
Example #10
Source File: Main.js    From semana-omnistack-10 with MIT License 4 votes vote down vote up
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>
    </>
  );
}
Example #11
Source File: Main.js    From FinDevs with MIT License 4 votes vote down vote up
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 #12
Source File: Main.js    From OmniStack-10.0 with MIT License 4 votes vote down vote up
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 #13
Source File: Mapa.js    From aglomerou with GNU General Public License v3.0 4 votes vote down vote up
export default function App() {
  const [localizacoes, setLocalizacoes] = useState([]);
  const [localInicial, setLocalInicial] = useState({
    latitude: 0,
    longitude: 0,
  });

  const [loading, setLoading] = useState(true);
  const [longName, setLongName] = useState('Você está aqui');

  const [modalMensagem, setModalMensagem] = useState(false);

  const mapRef = useRef();

  const moverMapa = async (novoLocal) => {
    console.log('movendo para o endereco recebido ->', novoLocal);

    const region = {
      latitude: novoLocal.lat,
      longitude: novoLocal.lng,
      latitudeDelta: 0.009,
      longitudeDelta: 0.009,
    };
    console.log('Atualiando markers. Novo local ->', novoLocal);

    mapRef.current.animateToRegion(region, 1200);

    const atualizaMarkers = await getMarkersRecentes();

    setLocalizacoes(atualizaMarkers);
  };

  const getMarkersRecentes = async () => {
    try {
      return await getLocalizacoesRecentes();
    } catch (error) {
      console.error(
        `Erro ao obter última localização dos dispositivos ativos: ${error}`
      );
      return error;
    }
  };

  // carrega localização e markers iniciais;
  useEffect(() => {
    let mounted = true;

    const getLocalizaoInicial = async () => {
      try {
        const { latitude, longitude } = await getLocalizacaoDispositivo();

        if (mounted) {
          setLocalInicial({
            latitude,
            longitude,
          });
          setLoading(false);
        }
      } catch (error) {
        console.error(`Erro ao obter localização inicial: ${error}`);

        // Define a localização inicial como Praça dos Girassóis.
        if (mounted) {
          setLocalInicial({
            latitude: -10.18451,
            longitude: -48.33466,
          });

          setLoading(false);
        }
      }
    };

    const getMarkersIniciais = async () => {
      const markers = await getMarkersRecentes();

      if (mounted) {
        setLocalizacoes(markers);
      }
    };

    getLocalizaoInicial();
    getMarkersIniciais();

    return () => {
      mounted = false;
    };
  }, []);

  // Inicia serviço de localização em background
  useEffect(() => {
    const start = async () => startLocationBackgroundUpdate();
    start();
  }, []);

  useEffect(() => {
    async function getLongNameNaLocalizacaoAtual() {
      try {
        setLongName(await getGeocodingLocalizacao());
      } catch (error) {
        console.log(error);
      }
    }

    getLongNameNaLocalizacaoAtual();
  }, []);

  useEffect(() => {
    let mounted = true;

    const checkModalVisto = async () => {
      const modalVisto = await AsyncStorage.getItem(MODAL_MAP_MESSAGE_ITEM);
      if (!modalVisto) {
        setModalMensagem(true);
      }
    };

    if (mounted) {
      checkModalVisto();
    }

    return () => {
      mounted = false;
    };
  }, []);

  const defineModalVisto = async () => {
    await AsyncStorage.setItem(MODAL_MAP_MESSAGE_ITEM, 'true');
    setModalMensagem(false);
  };

  return (
    <>
      <View style={styles.container}>
        {loading ? (
          <Text>Carregando Mapa...</Text>
        ) : (
          <>
            <MapView
              ref={mapRef}
              style={styles.mapStyle}
              initialRegion={{
                latitude: localInicial.latitude,
                longitude: localInicial.longitude,
                latitudeDelta: 0.05,
                longitudeDelta: 0.05,
              }}
            >
              <Marker
                key="minha_localizacao"
                title={longName}
                coordinate={{
                  latitude: localInicial.latitude,
                  longitude: localInicial.longitude,
                }}
              >
                <Mc name="circle-slice-8" size={24} color="#0000FF" />
              </Marker>
              {localizacoes.length > 0 ? (
                localizacoes.map((local) => (
                  <Marker
                    key={local + Math.random()}
                    coordinate={{
                      latitude: parseFloat(local.latitude),
                      longitude: parseFloat(local.longitude),
                    }}
                  >
                    <Fa name="map-marker-alt" size={32} color="#e02041" />
                  </Marker>
                ))
              ) : (
                <View />
              )}
            </MapView>
            <BarraPesquisa
              moverMapa={moverMapa}
              localizacaoInicial={localInicial}
            />
            <ModalMensagemMapa
              modalVisible={modalMensagem}
              fecharModal={defineModalVisto}
            />
            <BotaoExibeNoticias />
            <BotaoNotificar />
          </>
        )}
      </View>
    </>
  );
}
Example #14
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
ViewAssets = ({ organization, switchAssetPage }) => {
  useEffect(() => {
    let isSubscribed = true;

    async function fetchRegion() {
      await getData('assetMapRegion').then((data) => {
        if (isSubscribed) {
          if (!data) {
            setRegion({
              latitude: 18.4861,
              longitude: -69.9312,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            });
          } else {
            setRegion(data);
          }
        }
      });
    }

    fetchRegion();

    return () => { isSubscribed = false; };
  }, []);

  const [region, setRegion] = useState();
  const [markers, setMarkers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedMarker, setSelectedMarker] = useState();

  const handleLocation = async () => {
    setLoading(true);
    await getLocation().then((location) => {
      const { latitude, longitude } = location.coords;
      setRegion({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      });
      storeData({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      }, 'assetMapRegion');
    }).catch((e) => {
      console.log(e) //eslint-disable-line
    });
    setLoading(false);
  };

  const retrieveMarkers = () => {
    setLoading(true);
    assetDataQuery(organization).then((records) => {
      const sanitizedRecords = JSON.parse(JSON.stringify(records));
      setMarkers(sanitizedRecords);
      setLoading(false);
    }).catch((e) => {
      setLoading(false);
      console.log(e); //eslint-disable-line
    });
  };

  return (
    <View>
      <View style={styles.container}>
        <MapView
          style={styles.mapStyle}
          region={region}
        >
          {markers && markers.map((marker) => (
            marker.location && (
              <Marker
                key={marker.objectId}
                coordinate={marker.location}
                title={`${marker.name || ''}`}
                // description={`Collector: ${marker.surveyingOr}`}
                onPress={() => setSelectedMarker(marker)}
              />
            )
          ))}

        </MapView>
        <View style={styles.buttonStyle}>
          <IconButton
            icon="crosshairs-gps"
            onPress={handleLocation}
            color={theme.colors.primary}
            style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
          />
          <IconButton
            icon="refresh"
            onPress={retrieveMarkers}
            color={theme.colors.primary}
            style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
          />
        </View>
        {loading
          && <Spinner style={styles.loading} color={theme.colors.primary} />}

      </View>
      <View style={styles.container}>
        {selectedMarker
          && (
            <SelectedAsset
              selectedMarker={selectedMarker}
              style={{ position: 'absolute' }}
              switchAssetPage={switchAssetPage}
            />
          )}
      </View>
    </View>
  );
}
Example #15
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
Maps = ({ organization }) => {
  useEffect(() => {
    let isSubscribed = true;

    async function fetchRegion() {
      await getData('assetMapRegion').then((data) => {
        if (isSubscribed) {
          if (!data) {
            setRegion({
              latitude: 18.4861,
              longitude: -69.9312,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            });
          } else {
            setRegion(data);
          }
        }
      });
    }

    fetchRegion();

    return () => { isSubscribed = false; };
  }, []);

  const [region, setRegion] = useState();
  const [markers, setMarkers] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleLocation = async () => {
    setLoading(true);
    await getLocation().then((location) => {
      const { latitude, longitude } = location.coords;
      setRegion({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      });
      storeData({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      }, 'assetMapRegion');
    }).catch((e) => {
      console.log(e) //eslint-disable-line
    });
    setLoading(false);
  };

  const retrieveMarkers = () => {
    setLoading(true);
    const queryParams = {
      skip: 0,
      offset: 0,
      limit: 10000,
      parseColumn: 'surveyingOrganization',
      parseParam: organization,
    };
    residentIDQuery(queryParams).then((records) => {
      const sanitizedRecords = JSON.parse(JSON.stringify(records));
      setMarkers(sanitizedRecords);
      setLoading(false);
    }).catch((e) => {
      setLoading(false);
      console.log(e); //eslint-disable-line
    });
  };

  // const retriveAsyncMarkers = () => {
  //   setLoading(true);
  //   getData('residentData').then((residentData) => {
  //     if (residentData) {
  //       setMarkers(residentData);
  //     }
  //     setLoading(false);
  //   });
  // };

  // const retrieveOnlineMarkers = () => {
  //   setLoading(true);
  // const queryParams = {
  //   skip: 0,
  //   offset: 0,
  //   limit: 10000,
  //   parseColumn: 'surveyingOrganization',
  //   parseParam: organization,
  // };

  //   residentIDQuery(queryParams).then((recs) => {
  //     const records = JSON.parse(JSON.stringify(recs));
  //     setMarkers(records);
  //     setLoading(false);
  //   });
  // };

  return (
    <View style={styles.container}>
      <MapView
        style={styles.mapStyle}
        region={region}
      >
        {markers && markers.map((marker) => (
          marker.location && (
            <Marker
              key={marker.objectId}
              coordinate={marker.location}
              title={`${marker.fname || ''} ${marker.lname || ''}`}
              description={`Collector: ${marker.surveyingUser}`}
            />
          )
        ))}
      </MapView>
      {loading
        && <Spinner style={styles.loading} color={theme.colors.primary} />}
      <View style={styles.buttonStyle}>
        <IconButton
          icon="crosshairs-gps"
          onPress={handleLocation}
          color={theme.colors.primary}
          style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
        />
        <IconButton
          icon="refresh"
          onPress={retrieveMarkers}
          color={theme.colors.primary}
          style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
        />
      </View>
    </View>
  );
}
Example #16
Source File: Main.js    From devradar with MIT License 4 votes vote down vote up
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 #17
Source File: Cases.js    From react-native-covid19 with MIT License 4 votes vote down vote up
export default function Cases(props) {

	const activeTheme = useContext(theme).globalTheme;
	const darkTheme = useContext(theme).darkTheme;

	const styles = {
		container: {
			height: 250,
			width: '100%',
			position: 'relative',
			top: 0,
			zIndex: 10,
		},
		map: {
			position: 'absolute',
			top: 0,
			width: '100%',
			height: '100%'
		},
		searchContainer: {
			zIndex: 90,
			backgroundColor: activeTheme.darkTheme ? '#00000070' : '#ffffff70',
			width: '78%',
			position: 'absolute',
			right: 10,
			top: 20,
			// backgroundColor: 'transparent',
			borderWidth: 0,
			borderTopWidth: 0,
			borderBottomWidth: 0,
			borderRadius: 10,
			padding: 0,
			paddingHorizontal: 20,
			borderColor: activeTheme.textColor.secondary,
			borderBottomColor: activeTheme.textColor.secondary,
			borderTopColor: activeTheme.textColor.secondary
		}
	}


	const mapView = useRef(null);
	const [search, setSearch] = useState("");
	const [data, setData] = useState([]);

	const [filteredData, setFilteredData] = useState([]);

	const [forceListRerender, setForceListRerender] = useState(false);

	const [currentLatitude, setCurrentLatitude] = useState(35.8617);
	const [currentLongitude, setCurrentLongitude] = useState(104.1954);

	function updateSearch(search) {
		setSearch(search);
	}

	useEffect(() => {
		console.log(currentLatitude);
		console.log(currentLongitude);
	}, [currentLatitude, currentLongitude]);

	//filter data
	useEffect(() => {
		let newData;

		if (search.length > 0) {
			newData = data.filter((item) => {
				if (item) {
					return item.provinceState?.includes(search) || item.countryRegion?.includes(search);
				}
			})

		} else {
			console.log("new Data")
			newData = data;
		}

		setFilteredData(newData);

	}, [search, data]);

	useEffect(() => {
		setForceListRerender(!forceListRerender);
	}, [filteredData])

	function renderItem({ item }) {
		return (
			<CasesCard case={item} type={props.route.params['case']} onPress={() => setMapLocation(item.lat, item.long)} />
		)
	}

	function setMapLocation(latitude, longitude) {
		setCurrentLatitude(latitude);
		setCurrentLongitude(longitude);

		mapView.current.animateCamera({
			center: {
				latitude: currentLatitude,
				longitude: currentLongitude,
			},
			pitch: 1,
			heading: 0,
			zoom: 3
		})
	}

	useEffect(() => {
		getCases();
	}, [])

	async function getCases() {
		let caseType = props.route.params['case'];
		let response = await fetch(base_url + '/' + caseType.toLowerCase());

		if (response.status == 200) {
			let result = await response.json();

			setData(result, () => {
				setForceListRerender(!forceListRerender);
			});
		}
	}

	let markerColor;
	switch (props.route.params['case']) {
		case 'Confirmed':
			markerColor = activeTheme.textColor.confirmed;
			break;
		case 'Recovered':
			markerColor = activeTheme.textColor.recovered;
			break;
		case 'Deaths':
			markerColor = activeTheme.textColor.deaths;
	}
	return (
		<>
			<Button
				icon={
					<Icon
						name="arrow-back"
						type="material"
						color={activeTheme.textColor.secondary}
					/>
				}
				containerStyle={{ position: 'absolute', top: 20, left: 20, zIndex: 100 }}
				buttonStyle={{ backgroundColor: activeTheme.darkTheme ? '#00000070' : '#ffffff70', padding: 12 }}
				onPress={() => props.navigation.goBack()}
			/>
			<View style={styles.container}>
				<MapView
					ref={mapView}
					style={styles.map}
					initialCamera={{
						center: {
							latitude: 35.8617,
							longitude: 104.1954,
						},
						pitch: 1,
						heading: 0,
						zoom: 1
					}}
				>
					{data.map((item) => {
						return (
							<Marker
								coordinate={{
									longitude: item.long,
									latitude: item.lat
								}}
								pinColor={markerColor}
							/>)
					})}
				</MapView>
				{/* <View style={{}}> */}
				<SearchBar
					placeholder="Type City or province region"
					onChangeText={updateSearch}
					value={search}
					containerStyle={styles.searchContainer}
					inputContainerStyle={{ backgroundColor: 'transparent' }}
					inputStyle={{ color: activeTheme.textColor.secondary }}
					placeholderTextColor={activeTheme.textColor.secondary}
					searchIcon={{ color: activeTheme.textColor.secondary }}
				/>
				{/* </View> */}
			</View>
			<Container>
				<KeyboardAvoidingView>

					<View style={{ flex: 1, padding: 10 }}>
						<FlatList
							data={filteredData}
							renderItem={renderItem}
							extraData={forceListRerender}
						/>
					</View>
				</KeyboardAvoidingView>
			</Container>


		</>
	)
}
Example #18
Source File: index.js    From atendimento-e-agilidade-medica-AAMed with MIT License 4 votes vote down vote up
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 #19
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
Rumor = ({ navigation }) => {
    const { token, location, getCurrentLocation } = useUser()

    const [title, setTitle] = useState('')
    const [description, setDescription] = useState('')
    const [confirmedCases, setConfirmedCases] = useState(0)
    const [confirmedDeaths, setConfirmedDeaths] = useState(0)
    const [region, setRegion] = useState(location)
    const [modalVisible, setModalVisible] = useState(false)
    const [showMarker, setShowMarker] = useState(false)
    const [showAlert, setShowAlert] = useState(false)
    const [showProgressBar, setShowProgressBar] = useState(true)

    const eventInput = useRef()
    const casesInput = useRef()
    const deathsInput = useRef()

    useFocusEffect(
        useCallback(() => {
            getCurrentLocation()
        }, [])
    )

    const sendRumor = async () => {
        Keyboard.dismiss()

        const newRumor = {
            title,
            description,
            confirmed_cases: confirmedCases,
            confirmed_deaths: confirmedDeaths,
            latitude: region.latitude,
            longitude: region.longitude,
        }

        if (!validRumor(newRumor, showMarker)) return
        setShowAlert(true)

        const response = await createRumor({ rumor: newRumor }, token)

        if (response.status === 201) {
            setShowProgressBar(false)
        } else {
            Alert.alert(translate('register.geralError'))
            setShowAlert(false)
        }
    }

    return (
        <Container>
            <KeyboardScrollView>
                <Modal
                    transparent
                    visible={modalVisible}
                    onRequestClose={() => {
                        setModalVisible(!modalVisible)
                    }}
                >
                    <MapView
                        style={{ flex: 1 }}
                        region={region}
                        customMapStyle={mapStyle} // Android
                        userInterfaceStyle='dark' // iOS
                        showsUserLocation
                        onPress={(e) => {
                            console.warn(
                                'Show Marker',
                                e.nativeEvent.coordinate.latitude,
                                e.nativeEvent.coordinate.longitude
                            )

                            setShowMarker(true)
                            // When user scrolls through the map and clicks, the map goes back to where the
                            // the user is, thus is required userLatitude and userLongitude to be changed as well
                            setRegion({
                                ...region,
                                latitude: e.nativeEvent.coordinate.latitude,
                                longitude: e.nativeEvent.coordinate.longitude,
                            })
                        }}
                    >
                        {showMarker ? (
                            <Marker
                                coordinate={{
                                    latitude: region.latitude,
                                    longitude: region.longitude,
                                }}
                            />
                        ) : null}
                    </MapView>

                    <ExitMap
                        onPress={() => {
                            setShowMarker(false)
                            setRegion({
                                ...region,
                                latitude: location.latitude,
                                longitude: location.longitude,
                            })
                            setModalVisible(false)
                        }}
                    >
                        <Feather
                            name='x'
                            size={scale(25)}
                            color='#ffffff'
                            style={styles.icons}
                        />
                    </ExitMap>
                    {showMarker ? (
                        <ConfirmMap onPress={() => setModalVisible(false)}>
                            <Feather
                                name='check'
                                size={scale(25)}
                                color='#ffffff'
                                style={styles.icons}
                            />
                        </ConfirmMap>
                    ) : null}
                </Modal>

                <FormInline>
                    <FormLabel>Título:</FormLabel>
                    <NormalInput
                        maxLength={100}
                        onSubmitEditing={() => eventInput.current.focus()}
                        onChangeText={(text) => setTitle(text)}
                    />
                </FormInline>
                <FormInline>
                    <FormLabel>Descrição:</FormLabel>
                    <NormalInput
                        multiline
                        maxLength={300}
                        ref={eventInput}
                        onSubmitEditing={() => casesInput.current.focus()}
                        onChangeText={(text) => setDescription(text)}
                    />
                </FormInline>

                <FormGroup>
                    <FormGroupChild>
                        <FormLabel>Número de Casos:</FormLabel>
                        <NormalInput
                            keyboardType='number-pad'
                            ref={casesInput}
                            onSubmitEditing={() => deathsInput.current.focus()}
                            onChangeText={(text) => setConfirmedCases(text)}
                        />
                    </FormGroupChild>

                    <FormGroupChild>
                        <FormLabel>Número de Mortes:</FormLabel>
                        <NormalInput
                            keyboardType='number-pad'
                            ref={deathsInput}
                            onChangeText={(text) => setConfirmedDeaths(text)}
                        />
                    </FormGroupChild>
                </FormGroup>

                <FormGroup>
                    <FormGroupChild>
                        <FormLabel>Localização:</FormLabel>
                        <Button
                            onPress={() => {
                                Keyboard.dismiss()
                                setModalVisible(true)
                            }}
                        >
                            <MapFormMarker>
                                <MapFormText>Marcar no Mapa</MapFormText>
                                {showMarker ? (
                                    <Feather
                                        name='check-circle'
                                        size={scale(20)}
                                        color='#348EAC'
                                    />
                                ) : (
                                    <Feather
                                        name='x-circle'
                                        size={scale(20)}
                                        color='#c4c4c4'
                                    />
                                )}
                            </MapFormMarker>
                        </Button>
                    </FormGroupChild>
                </FormGroup>

                <Button onPress={() => sendRumor()}>
                    <SendContainer>
                        <SendText>Enviar</SendText>
                    </SendContainer>
                </Button>
            </KeyboardScrollView>

            <CoolAlert
                show={showAlert}
                showProgress={showProgressBar}
                title={
                    showProgressBar ? (
                        translate('badReport.messages.sending')
                    ) : (
                        <Text>
                            {translate('badReport.messages.thanks')}{' '}
                            {Emojis.tada}
                        </Text>
                    )
                }
                message={
                    showProgressBar ? null : (
                        <Text>{translate('rumor.rumorSent')}</Text>
                    )
                }
                closeOnTouchOutside={false}
                closeOnHardwareBackPress={false}
                showConfirmButton={!showProgressBar}
                confirmText={translate('badReport.messages.confirmText')}
                onConfirmPressed={() => navigation.goBack()}
                onDismiss={() => setShowAlert(false)}
            />
        </Container>
    )
}
Example #20
Source File: index.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
Maps = () => {
    const {
        isOffline,
        token,
        getCurrentLocation,
        getAppTip,
        hideAppTip,
        getCacheData,
    } = useUser()

    const [isLoading, setIsLoading] = useState(true)
    const [region, setRegion] = useState(initialRegion)
    const [mapKey, setMapKey] = useState(0)
    const [showAlert, setShowAlert] = useState(false)
    const [showUserLocation, setShowUserLocation] = useState(false)
    const [weekSurveys, setWeekSurveys] = useState([])
    const [filteredSurveys, setFilteredSurveys] = useState([])
    const [showPolygon, setShowPolygon] = useState(false)
    const [polygonState, setPolygonState] = useState('Federal District')

    useFocusEffect(
        useCallback(() => {
            getMapPins()
        }, [])
    )

    useEffect(() => {
        if (getAppTip('mapTip')) {
            setShowAlert(true)
        }
    }, [])

    const getMapPins = async () => {
        const local = await getCurrentLocation()

        if (local.error === 0) {
            setRegion(local)
            setShowUserLocation(true)
            setMapKey(mapKey + 1)
        }

        if (!isOffline && isLoading) {
            const localPin = await getCacheData('localPin', false)
            await getSurveys(localPin)
        }
    }

    const getSurveys = async (localPin) => {
        // Get Week Surveys
        const response = await getWeekSurveys(token)

        if (response.status === 200) {
            if (localPin) {
                setWeekSurveys([...response.data.surveys, localPin])
            } else {
                setWeekSurveys(response.data.surveys)
            }

            setIsLoading(false)
            // getSurveyPerState() // Logica que filtra casos de covid
        }
    }

    const hideAlert = async () => {
        setShowAlert(false)
        hideAppTip('mapTip')
    }

    const getSurveyPerState = async () => {
        const dataFilterd = []
        let reportsInState = 0
        let badReportsInState = 0
        let covidCasesInState = 0

        weekSurveys.forEach((data) => {
            if (data.state === polygonState) {
                reportsInState += 1
                if (data.symptom && data.symptom.length) {
                    badReportsInState += 1
                    if (
                        data.symptom.includes('Febre') &&
                        (data.symptom.includes('DordeGarganta') ||
                            data.symptom.includes('DificuldadeParaRespirar') ||
                            data.symptom.includes('Tosse') ||
                            data.symptom.includes('Cansaco') ||
                            data.symptom.includes('Mal-estar'))
                    ) {
                        dataFilterd.push(data)
                        covidCasesInState += 1
                    }
                }
            }
        })

        setFilteredSurveys(dataFilterd)
    }

    const CoordInsidePolygon = (point, vs) => {
        // ray-casting algorithm based on
        // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

        const x = point[0]
        const y = point[1]

        let inside = false
        for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
            const xi = vs[i][0]
            const yi = vs[i][1]
            const xj = vs[j][0]
            const yj = vs[j][1]

            const intersect =
                yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi
            if (intersect) inside = !inside
        }

        return inside
    }

    const PolygonColor = (numCase, maxCase) => {
        let colorR = 0
        let colorG = 0

        if (numCase === 0) {
            fillColor = 'rgba(0, 0, 0, 0.0)'
        } else if (numCase <= maxCase / 2) {
            colorR = (255 * numCase) / (maxCase / 2)
            fillColor = `rgba(${parseInt(colorR, 10)}, 255, 0, 0.5)`
        } else {
            colorG = 255 - (255 * numCase) / maxCase
            fillColor = `rgba(255, ${parseInt(colorG, 10)}, 0, 0.5)`
        }
        return fillColor
    }

    const coordsFilter = () => {
        const markers = []
        weekSurveys.forEach((mark) => {
            markers.push({
                location: {
                    latitude: mark.latitude,
                    longitude: mark.longitude,
                },
                symptoms: mark.symptom && mark.symptom.length > 0,
            })
        })
        return markers
    }

    const renderGoodMarker = (data) => (
        <Marker
            key={data.id || Math.random()}
            coordinate={data.location}
            image={greenMarker}
            tracksViewChanges={false}
        />
    )

    const renderBadMarker = (data) => (
        <Marker
            key={data.id || Math.random()}
            coordinate={data.location}
            image={redMarker}
            tracksViewChanges={false}
        />
    )

    return (
        <>
            <SafeAreaView style={{ flex: 0, backgroundColor: '#348EAC' }} />
            <Container>
                <ClusteredMapView
                    key={mapKey} // Updates Map
                    showsUserLocation={showUserLocation}
                    style={styles.map}
                    data={coordsFilter()}
                    initialRegion={region}
                    customMapStyle={mapStyle} // Android
                    userInterfaceStyle='dark' // iOS
                    renderMarker={{
                        good: renderGoodMarker,
                        bad: renderBadMarker,
                    }}
                    CLUSTER_SIZE_DIVIDER={CLUSTER_SIZE_DIVIDER} // The log of number of points in cluster by this constant's base defines cluster image size
                    screenSizeClusterPercentage={0.13} // Cluster occupies 13% of screen
                />
                <CoolAlert
                    show={showAlert}
                    message={translate('maps.guide')}
                    showConfirmButton
                    confirmText={translate('maps.confirmGuide')}
                    onConfirmPressed={() => hideAlert()}
                />
                {/*
                <ButtonMapChange
                    onPress={() => {
                        !showPolygon
                            ? setShowPolygon(true)
                            : setShowPolygon(false)
                    }}
                >
                    <TextMapChange>
                        Visualizar {!showPolygon ? 'Poligonos' : 'Mapa'}
                    </TextMapChange>
                </ButtonMapChange>
                */}
            </Container>
        </>
    )
}
Example #21
Source File: Main.js    From SemanaOmnistack10 with MIT License 4 votes vote down vote up
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>
        </>
    );
}